Harbor format: 871 coding_baseline tasks (part 42)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/test.sh +6 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted-inventory.json +102 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/pyproject.toml +93 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/__init__.py +0 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/base.py +354 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/conftest.py +27 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/foo_serializer.py +5 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/mypy_test_cases/test_validation_error.py +20 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_decorators.py +896 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_deserialization.py +2298 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_error_store.py +143 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_exceptions.py +42 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_fields.py +665 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_options.py +280 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_registry.py +216 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_schema.py +2950 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_serialization.py +1041 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_utils.py +282 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_validate.py +983 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_version_attributes.py +15 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tox.ini +35 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/canaries/first-hunk-only.sh +29 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/canaries/original-bug.sh +3 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/openenv.json +27 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/LICENSE.source +19 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/adapter.json +127 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/dependency-setup.sh +8 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/environment/Dockerfile +3 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/instruction.md +42 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/metadata.json +0 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/provenance.json +88 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/provided-gold.diff +47 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/solution/solve.sh +53 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/task.toml +24 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/check_pytest.py +177 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/expected-panels.json +0 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/grade.py +128 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/panel-config.json +23 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/test.sh +6 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted-inventory.json +102 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/pyproject.toml +93 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/__init__.py +0 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/base.py +354 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/conftest.py +27 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/foo_serializer.py +5 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/mypy_test_cases/test_validation_error.py +20 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_decorators.py +896 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_deserialization.py +2298 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_error_store.py +143 -0
- tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_exceptions.py +42 -0
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/test.sh
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -Eeuo pipefail
|
| 3 |
+
source /opt/miniconda3/bin/activate
|
| 4 |
+
conda activate testbed
|
| 5 |
+
cd /testbed/repo
|
| 6 |
+
exec python -I /tests/grade.py
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted-inventory.json
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"directory_roots": [
|
| 3 |
+
"tests"
|
| 4 |
+
],
|
| 5 |
+
"files": {
|
| 6 |
+
"pyproject.toml": {
|
| 7 |
+
"bytes": 2514,
|
| 8 |
+
"mode": 420,
|
| 9 |
+
"sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd"
|
| 10 |
+
},
|
| 11 |
+
"tests/__init__.py": {
|
| 12 |
+
"bytes": 0,
|
| 13 |
+
"mode": 420,
|
| 14 |
+
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
| 15 |
+
},
|
| 16 |
+
"tests/base.py": {
|
| 17 |
+
"bytes": 8963,
|
| 18 |
+
"mode": 420,
|
| 19 |
+
"sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3"
|
| 20 |
+
},
|
| 21 |
+
"tests/conftest.py": {
|
| 22 |
+
"bytes": 566,
|
| 23 |
+
"mode": 420,
|
| 24 |
+
"sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057"
|
| 25 |
+
},
|
| 26 |
+
"tests/foo_serializer.py": {
|
| 27 |
+
"bytes": 97,
|
| 28 |
+
"mode": 420,
|
| 29 |
+
"sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91"
|
| 30 |
+
},
|
| 31 |
+
"tests/mypy_test_cases/test_validation_error.py": {
|
| 32 |
+
"bytes": 579,
|
| 33 |
+
"mode": 420,
|
| 34 |
+
"sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab"
|
| 35 |
+
},
|
| 36 |
+
"tests/test_decorators.py": {
|
| 37 |
+
"bytes": 30937,
|
| 38 |
+
"mode": 420,
|
| 39 |
+
"sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5"
|
| 40 |
+
},
|
| 41 |
+
"tests/test_deserialization.py": {
|
| 42 |
+
"bytes": 88128,
|
| 43 |
+
"mode": 420,
|
| 44 |
+
"sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2"
|
| 45 |
+
},
|
| 46 |
+
"tests/test_error_store.py": {
|
| 47 |
+
"bytes": 5137,
|
| 48 |
+
"mode": 420,
|
| 49 |
+
"sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f"
|
| 50 |
+
},
|
| 51 |
+
"tests/test_exceptions.py": {
|
| 52 |
+
"bytes": 1416,
|
| 53 |
+
"mode": 420,
|
| 54 |
+
"sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77"
|
| 55 |
+
},
|
| 56 |
+
"tests/test_fields.py": {
|
| 57 |
+
"bytes": 24578,
|
| 58 |
+
"mode": 420,
|
| 59 |
+
"sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf"
|
| 60 |
+
},
|
| 61 |
+
"tests/test_options.py": {
|
| 62 |
+
"bytes": 7852,
|
| 63 |
+
"mode": 420,
|
| 64 |
+
"sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de"
|
| 65 |
+
},
|
| 66 |
+
"tests/test_registry.py": {
|
| 67 |
+
"bytes": 6907,
|
| 68 |
+
"mode": 420,
|
| 69 |
+
"sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e"
|
| 70 |
+
},
|
| 71 |
+
"tests/test_schema.py": {
|
| 72 |
+
"bytes": 92822,
|
| 73 |
+
"mode": 420,
|
| 74 |
+
"sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f"
|
| 75 |
+
},
|
| 76 |
+
"tests/test_serialization.py": {
|
| 77 |
+
"bytes": 39066,
|
| 78 |
+
"mode": 420,
|
| 79 |
+
"sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f"
|
| 80 |
+
},
|
| 81 |
+
"tests/test_utils.py": {
|
| 82 |
+
"bytes": 7716,
|
| 83 |
+
"mode": 420,
|
| 84 |
+
"sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59"
|
| 85 |
+
},
|
| 86 |
+
"tests/test_validate.py": {
|
| 87 |
+
"bytes": 32663,
|
| 88 |
+
"mode": 420,
|
| 89 |
+
"sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd"
|
| 90 |
+
},
|
| 91 |
+
"tests/test_version_attributes.py": {
|
| 92 |
+
"bytes": 336,
|
| 93 |
+
"mode": 420,
|
| 94 |
+
"sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345"
|
| 95 |
+
},
|
| 96 |
+
"tox.ini": {
|
| 97 |
+
"bytes": 827,
|
| 98 |
+
"mode": 420,
|
| 99 |
+
"sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877"
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
}
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/pyproject.toml
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "marshmallow"
|
| 3 |
+
version = "3.23.1"
|
| 4 |
+
description = "A lightweight library for converting complex datatypes to and from native Python datatypes."
|
| 5 |
+
readme = "README.rst"
|
| 6 |
+
license = { file = "LICENSE" }
|
| 7 |
+
authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }]
|
| 8 |
+
maintainers = [
|
| 9 |
+
{ name = "Steven Loria", email = "sloria1@gmail.com" },
|
| 10 |
+
{ name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" },
|
| 11 |
+
{ name = "Jared Deckard", email = "jared@shademaps.com" },
|
| 12 |
+
]
|
| 13 |
+
classifiers = [
|
| 14 |
+
"Development Status :: 5 - Production/Stable",
|
| 15 |
+
"Intended Audience :: Developers",
|
| 16 |
+
"License :: OSI Approved :: MIT License",
|
| 17 |
+
"Programming Language :: Python :: 3",
|
| 18 |
+
"Programming Language :: Python :: 3.9",
|
| 19 |
+
"Programming Language :: Python :: 3.10",
|
| 20 |
+
"Programming Language :: Python :: 3.11",
|
| 21 |
+
"Programming Language :: Python :: 3.12",
|
| 22 |
+
"Programming Language :: Python :: 3.13",
|
| 23 |
+
]
|
| 24 |
+
requires-python = ">=3.9"
|
| 25 |
+
dependencies = ["packaging>=17.0"]
|
| 26 |
+
|
| 27 |
+
[project.urls]
|
| 28 |
+
Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html"
|
| 29 |
+
Funding = "https://opencollective.com/marshmallow"
|
| 30 |
+
Issues = "https://github.com/marshmallow-code/marshmallow/issues"
|
| 31 |
+
Source = "https://github.com/marshmallow-code/marshmallow"
|
| 32 |
+
Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi"
|
| 33 |
+
|
| 34 |
+
[project.optional-dependencies]
|
| 35 |
+
docs = [
|
| 36 |
+
"sphinx==8.1.3",
|
| 37 |
+
"sphinx-issues==5.0.0",
|
| 38 |
+
"alabaster==1.0.0",
|
| 39 |
+
"sphinx-version-warning==1.1.2",
|
| 40 |
+
"autodocsumm==0.2.14",
|
| 41 |
+
]
|
| 42 |
+
tests = ["pytest", "simplejson"]
|
| 43 |
+
dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"]
|
| 44 |
+
|
| 45 |
+
[build-system]
|
| 46 |
+
requires = ["flit_core<4"]
|
| 47 |
+
build-backend = "flit_core.buildapi"
|
| 48 |
+
|
| 49 |
+
[tool.flit.sdist]
|
| 50 |
+
include = [
|
| 51 |
+
"docs/",
|
| 52 |
+
"tests/",
|
| 53 |
+
"CHANGELOG.rst",
|
| 54 |
+
"CONTRIBUTING.rst",
|
| 55 |
+
"SECURITY.md",
|
| 56 |
+
"NOTICE",
|
| 57 |
+
"tox.ini",
|
| 58 |
+
]
|
| 59 |
+
exclude = ["docs/_build/"]
|
| 60 |
+
|
| 61 |
+
[tool.ruff]
|
| 62 |
+
src = ["src"]
|
| 63 |
+
fix = true
|
| 64 |
+
show-fixes = true
|
| 65 |
+
output-format = "full"
|
| 66 |
+
|
| 67 |
+
[tool.ruff.format]
|
| 68 |
+
docstring-code-format = true
|
| 69 |
+
|
| 70 |
+
[tool.ruff.lint]
|
| 71 |
+
ignore = ["E203", "E266", "E501", "E731"]
|
| 72 |
+
select = [
|
| 73 |
+
"B", # flake8-bugbear
|
| 74 |
+
"E", # pycodestyle error
|
| 75 |
+
"F", # pyflakes
|
| 76 |
+
"I", # isort
|
| 77 |
+
"UP", # pyupgrade
|
| 78 |
+
"W", # pycodestyle warning
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
[tool.ruff.lint.per-file-ignores]
|
| 82 |
+
"tests/*" = ["E721"]
|
| 83 |
+
|
| 84 |
+
[tool.mypy]
|
| 85 |
+
ignore_missing_imports = true
|
| 86 |
+
warn_unreachable = true
|
| 87 |
+
warn_unused_ignores = true
|
| 88 |
+
warn_redundant_casts = true
|
| 89 |
+
no_implicit_optional = true
|
| 90 |
+
|
| 91 |
+
[tool.pytest.ini_options]
|
| 92 |
+
norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases"
|
| 93 |
+
addopts = "-v --tb=short"
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/__init__.py
ADDED
|
File without changes
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/base.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test utilities and fixtures."""
|
| 2 |
+
|
| 3 |
+
import datetime as dt
|
| 4 |
+
import functools
|
| 5 |
+
import uuid
|
| 6 |
+
from enum import Enum, IntEnum
|
| 7 |
+
from zoneinfo import ZoneInfo
|
| 8 |
+
|
| 9 |
+
import simplejson
|
| 10 |
+
|
| 11 |
+
from marshmallow import Schema, fields, missing, post_load, validate
|
| 12 |
+
from marshmallow.exceptions import ValidationError
|
| 13 |
+
|
| 14 |
+
central = ZoneInfo("America/Chicago")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class GenderEnum(IntEnum):
|
| 18 |
+
male = 1
|
| 19 |
+
female = 2
|
| 20 |
+
non_binary = 3
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class HairColorEnum(Enum):
|
| 24 |
+
black = "black hair"
|
| 25 |
+
brown = "brown hair"
|
| 26 |
+
blond = "blond hair"
|
| 27 |
+
red = "red hair"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DateEnum(Enum):
|
| 31 |
+
date_1 = dt.date(2004, 2, 29)
|
| 32 |
+
date_2 = dt.date(2008, 2, 29)
|
| 33 |
+
date_3 = dt.date(2012, 2, 29)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
ALL_FIELDS = [
|
| 37 |
+
fields.String,
|
| 38 |
+
fields.Integer,
|
| 39 |
+
fields.Boolean,
|
| 40 |
+
fields.Float,
|
| 41 |
+
fields.Number,
|
| 42 |
+
fields.DateTime,
|
| 43 |
+
fields.Time,
|
| 44 |
+
fields.Date,
|
| 45 |
+
fields.TimeDelta,
|
| 46 |
+
fields.Dict,
|
| 47 |
+
fields.Url,
|
| 48 |
+
fields.Email,
|
| 49 |
+
fields.UUID,
|
| 50 |
+
fields.Decimal,
|
| 51 |
+
fields.IP,
|
| 52 |
+
fields.IPv4,
|
| 53 |
+
fields.IPv6,
|
| 54 |
+
fields.IPInterface,
|
| 55 |
+
fields.IPv4Interface,
|
| 56 |
+
fields.IPv6Interface,
|
| 57 |
+
functools.partial(fields.Enum, GenderEnum),
|
| 58 |
+
functools.partial(fields.Enum, HairColorEnum, by_value=fields.String),
|
| 59 |
+
functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer),
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
##### Custom asserts #####
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def assert_date_equal(d1, d2):
|
| 67 |
+
assert d1.year == d2.year
|
| 68 |
+
assert d1.month == d2.month
|
| 69 |
+
assert d1.day == d2.day
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def assert_time_equal(t1, t2):
|
| 73 |
+
assert t1.hour == t2.hour
|
| 74 |
+
assert t1.minute == t2.minute
|
| 75 |
+
assert t1.second == t2.second
|
| 76 |
+
assert t1.microsecond == t2.microsecond
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
##### Models #####
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class User:
|
| 83 |
+
SPECIES = "Homo sapiens"
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
name,
|
| 88 |
+
age=0,
|
| 89 |
+
id_=None,
|
| 90 |
+
homepage=None,
|
| 91 |
+
email=None,
|
| 92 |
+
registered=True,
|
| 93 |
+
time_registered=None,
|
| 94 |
+
birthdate=None,
|
| 95 |
+
birthtime=None,
|
| 96 |
+
balance=100,
|
| 97 |
+
sex=GenderEnum.male,
|
| 98 |
+
hair_color=HairColorEnum.black,
|
| 99 |
+
employer=None,
|
| 100 |
+
various_data=None,
|
| 101 |
+
):
|
| 102 |
+
self.name = name
|
| 103 |
+
self.age = age
|
| 104 |
+
# A naive datetime
|
| 105 |
+
self.created = dt.datetime(2013, 11, 10, 14, 20, 58)
|
| 106 |
+
# A TZ-aware datetime
|
| 107 |
+
self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central)
|
| 108 |
+
self.id = id_
|
| 109 |
+
self.homepage = homepage
|
| 110 |
+
self.email = email
|
| 111 |
+
self.balance = balance
|
| 112 |
+
self.registered = registered
|
| 113 |
+
self.hair_colors = list(HairColorEnum.__members__)
|
| 114 |
+
self.sex_choices = list(GenderEnum.__members__)
|
| 115 |
+
self.finger_count = 10
|
| 116 |
+
self.uid = uuid.uuid1()
|
| 117 |
+
self.time_registered = time_registered or dt.time(1, 23, 45, 6789)
|
| 118 |
+
self.birthdate = birthdate or dt.date(2013, 1, 23)
|
| 119 |
+
self.birthtime = birthtime or dt.time(0, 1, 2, 3333)
|
| 120 |
+
self.activation_date = dt.date(2013, 12, 11)
|
| 121 |
+
self.sex = sex
|
| 122 |
+
self.hair_color = hair_color
|
| 123 |
+
self.employer = employer
|
| 124 |
+
self.relatives = []
|
| 125 |
+
self.various_data = various_data or {
|
| 126 |
+
"pets": ["cat", "dog"],
|
| 127 |
+
"address": "1600 Pennsylvania Ave\n" "Washington, DC 20006",
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def since_created(self):
|
| 132 |
+
return dt.datetime(2013, 11, 24) - self.created
|
| 133 |
+
|
| 134 |
+
def __repr__(self):
|
| 135 |
+
return f"<User {self.name}>"
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class Blog:
|
| 139 |
+
def __init__(self, title, user, collaborators=None, categories=None, id_=None):
|
| 140 |
+
self.title = title
|
| 141 |
+
self.user = user
|
| 142 |
+
self.collaborators = collaborators or [] # List/tuple of users
|
| 143 |
+
self.categories = categories
|
| 144 |
+
self.id = id_
|
| 145 |
+
|
| 146 |
+
def __contains__(self, item):
|
| 147 |
+
return item.name in [each.name for each in self.collaborators]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class DummyModel:
|
| 151 |
+
def __init__(self, foo):
|
| 152 |
+
self.foo = foo
|
| 153 |
+
|
| 154 |
+
def __eq__(self, other):
|
| 155 |
+
return self.foo == other.foo
|
| 156 |
+
|
| 157 |
+
def __str__(self):
|
| 158 |
+
return f"bar {self.foo}"
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
###### Schemas #####
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class Uppercased(fields.Field):
|
| 165 |
+
"""Custom field formatting example."""
|
| 166 |
+
|
| 167 |
+
def _serialize(self, value, attr, obj):
|
| 168 |
+
if value:
|
| 169 |
+
return value.upper()
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def get_lowername(obj):
|
| 173 |
+
if obj is None:
|
| 174 |
+
return missing
|
| 175 |
+
if isinstance(obj, dict):
|
| 176 |
+
return obj.get("name").lower()
|
| 177 |
+
else:
|
| 178 |
+
return obj.name.lower()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class UserSchema(Schema):
|
| 182 |
+
name = fields.String()
|
| 183 |
+
age = fields.Float() # type: fields.Field
|
| 184 |
+
created = fields.DateTime()
|
| 185 |
+
created_formatted = fields.DateTime(
|
| 186 |
+
format="%Y-%m-%d", attribute="created", dump_only=True
|
| 187 |
+
)
|
| 188 |
+
created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True)
|
| 189 |
+
updated = fields.DateTime()
|
| 190 |
+
species = fields.String(attribute="SPECIES")
|
| 191 |
+
id = fields.String(dump_default="no-id")
|
| 192 |
+
uppername = Uppercased(attribute="name", dump_only=True)
|
| 193 |
+
homepage = fields.Url()
|
| 194 |
+
email = fields.Email()
|
| 195 |
+
balance = fields.Decimal()
|
| 196 |
+
is_old = fields.Method("get_is_old") # type: fields.Field
|
| 197 |
+
lowername = fields.Function(get_lowername)
|
| 198 |
+
registered = fields.Boolean()
|
| 199 |
+
hair_colors = fields.List(fields.Raw)
|
| 200 |
+
sex_choices = fields.List(fields.Raw)
|
| 201 |
+
finger_count = fields.Integer()
|
| 202 |
+
uid = fields.UUID()
|
| 203 |
+
time_registered = fields.Time()
|
| 204 |
+
birthdate = fields.Date()
|
| 205 |
+
birthtime = fields.Time()
|
| 206 |
+
activation_date = fields.Date()
|
| 207 |
+
since_created = fields.TimeDelta()
|
| 208 |
+
sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__)))
|
| 209 |
+
various_data = fields.Dict()
|
| 210 |
+
|
| 211 |
+
class Meta:
|
| 212 |
+
render_module = simplejson
|
| 213 |
+
|
| 214 |
+
def get_is_old(self, obj):
|
| 215 |
+
if obj is None:
|
| 216 |
+
return missing
|
| 217 |
+
if isinstance(obj, dict):
|
| 218 |
+
age = obj.get("age")
|
| 219 |
+
else:
|
| 220 |
+
age = obj.age
|
| 221 |
+
try:
|
| 222 |
+
return age > 80
|
| 223 |
+
except TypeError as te:
|
| 224 |
+
raise ValidationError(str(te)) from te
|
| 225 |
+
|
| 226 |
+
@post_load
|
| 227 |
+
def make_user(self, data, **kwargs):
|
| 228 |
+
return User(**data)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class UserMetaSchema(Schema):
|
| 232 |
+
"""The equivalent of the UserSchema, using the ``fields`` option."""
|
| 233 |
+
|
| 234 |
+
uppername = Uppercased(attribute="name", dump_only=True)
|
| 235 |
+
balance = fields.Decimal()
|
| 236 |
+
is_old = fields.Method("get_is_old")
|
| 237 |
+
lowername = fields.Function(get_lowername)
|
| 238 |
+
species = fields.String(attribute="SPECIES")
|
| 239 |
+
homepage = fields.Url()
|
| 240 |
+
email = fields.Email()
|
| 241 |
+
various_data = fields.Dict()
|
| 242 |
+
|
| 243 |
+
def get_is_old(self, obj):
|
| 244 |
+
if obj is None:
|
| 245 |
+
return missing
|
| 246 |
+
if isinstance(obj, dict):
|
| 247 |
+
age = obj.get("age")
|
| 248 |
+
else:
|
| 249 |
+
age = obj.age
|
| 250 |
+
try:
|
| 251 |
+
return age > 80
|
| 252 |
+
except TypeError as te:
|
| 253 |
+
raise ValidationError(str(te)) from te
|
| 254 |
+
|
| 255 |
+
class Meta:
|
| 256 |
+
fields = (
|
| 257 |
+
"name",
|
| 258 |
+
"age",
|
| 259 |
+
"created",
|
| 260 |
+
"updated",
|
| 261 |
+
"id",
|
| 262 |
+
"homepage",
|
| 263 |
+
"uppername",
|
| 264 |
+
"email",
|
| 265 |
+
"balance",
|
| 266 |
+
"is_old",
|
| 267 |
+
"lowername",
|
| 268 |
+
"species",
|
| 269 |
+
"registered",
|
| 270 |
+
"hair_colors",
|
| 271 |
+
"sex_choices",
|
| 272 |
+
"finger_count",
|
| 273 |
+
"uid",
|
| 274 |
+
"time_registered",
|
| 275 |
+
"birthdate",
|
| 276 |
+
"birthtime",
|
| 277 |
+
"since_created",
|
| 278 |
+
"various_data",
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class UserExcludeSchema(UserSchema):
|
| 283 |
+
class Meta:
|
| 284 |
+
exclude = ("created", "updated")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class UserAdditionalSchema(Schema):
|
| 288 |
+
lowername = fields.Function(lambda obj: obj.name.lower())
|
| 289 |
+
|
| 290 |
+
class Meta:
|
| 291 |
+
additional = ("name", "age", "created", "email")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class UserIntSchema(UserSchema):
|
| 295 |
+
age = fields.Integer()
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class UserFloatStringSchema(UserSchema):
|
| 299 |
+
age = fields.Float(as_string=True)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class ExtendedUserSchema(UserSchema):
|
| 303 |
+
is_old = fields.Boolean()
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
class UserRelativeUrlSchema(UserSchema):
|
| 307 |
+
homepage = fields.Url(relative=True)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class BlogSchema(Schema):
|
| 311 |
+
title = fields.String()
|
| 312 |
+
user = fields.Nested(UserSchema)
|
| 313 |
+
collaborators = fields.List(fields.Nested(UserSchema()))
|
| 314 |
+
categories = fields.List(fields.String)
|
| 315 |
+
id = fields.String()
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class BlogUserMetaSchema(Schema):
|
| 319 |
+
user = fields.Nested(UserMetaSchema())
|
| 320 |
+
collaborators = fields.List(fields.Nested(UserMetaSchema()))
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class BlogSchemaMeta(Schema):
|
| 324 |
+
"""Same as BlogSerializer but using ``fields`` options."""
|
| 325 |
+
|
| 326 |
+
user = fields.Nested(UserSchema)
|
| 327 |
+
collaborators = fields.List(fields.Nested(UserSchema()))
|
| 328 |
+
|
| 329 |
+
class Meta:
|
| 330 |
+
fields = ("title", "user", "collaborators", "categories", "id")
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class BlogOnlySchema(Schema):
|
| 334 |
+
title = fields.String()
|
| 335 |
+
user = fields.Nested(UserSchema)
|
| 336 |
+
collaborators = fields.List(fields.Nested(UserSchema(only=("id",))))
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class BlogSchemaExclude(BlogSchema):
|
| 340 |
+
user = fields.Nested(UserSchema, exclude=("uppername", "species"))
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class BlogSchemaOnlyExclude(BlogSchema):
|
| 344 |
+
user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species"))
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
class mockjson: # noqa
|
| 348 |
+
@staticmethod
|
| 349 |
+
def dumps(val):
|
| 350 |
+
return b"{'foo': 42}"
|
| 351 |
+
|
| 352 |
+
@staticmethod
|
| 353 |
+
def loads(val):
|
| 354 |
+
return {"foo": 42}
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/conftest.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pytest fixtures that are available in all test modules."""
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from tests.base import Blog, User, UserSchema
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.fixture
|
| 9 |
+
def user():
|
| 10 |
+
return User(name="Monty", age=42.3, homepage="http://monty.python.org/")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.fixture
|
| 14 |
+
def blog(user):
|
| 15 |
+
col1 = User(name="Mick", age=123)
|
| 16 |
+
col2 = User(name="Keith", age=456)
|
| 17 |
+
return Blog(
|
| 18 |
+
"Monty's blog",
|
| 19 |
+
user=user,
|
| 20 |
+
categories=["humor", "violence"],
|
| 21 |
+
collaborators=[col1, col2],
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.fixture
|
| 26 |
+
def serialized_user(user):
|
| 27 |
+
return UserSchema().dump(user)
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/foo_serializer.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from marshmallow import Schema, fields
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class FooSerializer(Schema):
|
| 5 |
+
_id = fields.Integer()
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/mypy_test_cases/test_validation_error.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import marshmallow as ma
|
| 4 |
+
|
| 5 |
+
# OK types for 'message'
|
| 6 |
+
ma.ValidationError("foo")
|
| 7 |
+
ma.ValidationError(["foo"])
|
| 8 |
+
ma.ValidationError({"foo": "bar"})
|
| 9 |
+
|
| 10 |
+
# non-OK types for 'message'
|
| 11 |
+
ma.ValidationError(0) # type: ignore[arg-type]
|
| 12 |
+
|
| 13 |
+
# 'messages' is a dict|list
|
| 14 |
+
err = ma.ValidationError("foo")
|
| 15 |
+
a: dict | list = err.messages
|
| 16 |
+
# union type can't assign to non-union type
|
| 17 |
+
b: str = err.messages # type: ignore[assignment]
|
| 18 |
+
c: dict = err.messages # type: ignore[assignment]
|
| 19 |
+
# 'messages_dict' is a dict, so that it can assign to a dict
|
| 20 |
+
d: dict = err.messages_dict
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_decorators.py
ADDED
|
@@ -0,0 +1,896 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 12 |
+
pre_dump,
|
| 13 |
+
pre_load,
|
| 14 |
+
validates,
|
| 15 |
+
validates_schema,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest.mark.parametrize("partial_val", (True, False))
|
| 20 |
+
def test_decorated_processors(partial_val):
|
| 21 |
+
class ExampleSchema(Schema):
|
| 22 |
+
"""Includes different ways to invoke decorators and set up methods"""
|
| 23 |
+
|
| 24 |
+
TAG = "TAG"
|
| 25 |
+
|
| 26 |
+
value = fields.Integer(as_string=True)
|
| 27 |
+
|
| 28 |
+
# Implicit default raw, pre dump, static method.
|
| 29 |
+
@pre_dump
|
| 30 |
+
def increment_value(self, item, **kwargs):
|
| 31 |
+
assert "many" in kwargs
|
| 32 |
+
item["value"] += 1
|
| 33 |
+
return item
|
| 34 |
+
|
| 35 |
+
# Implicit default raw, post dump, class method.
|
| 36 |
+
@post_dump
|
| 37 |
+
def add_tag(self, item, **kwargs):
|
| 38 |
+
assert "many" in kwargs
|
| 39 |
+
item["value"] = self.TAG + item["value"]
|
| 40 |
+
return item
|
| 41 |
+
|
| 42 |
+
# Explicitly raw, post dump, instance method.
|
| 43 |
+
@post_dump(pass_many=True)
|
| 44 |
+
def add_envelope(self, data, many, **kwargs):
|
| 45 |
+
key = self.get_envelope_key(many)
|
| 46 |
+
return {key: data}
|
| 47 |
+
|
| 48 |
+
# Explicitly raw, pre load, instance method.
|
| 49 |
+
@pre_load(pass_many=True)
|
| 50 |
+
def remove_envelope(self, data, many, partial, **kwargs):
|
| 51 |
+
assert partial is partial_val
|
| 52 |
+
key = self.get_envelope_key(many)
|
| 53 |
+
return data[key]
|
| 54 |
+
|
| 55 |
+
@staticmethod
|
| 56 |
+
def get_envelope_key(many):
|
| 57 |
+
return "data" if many else "datum"
|
| 58 |
+
|
| 59 |
+
# Explicitly not raw, pre load, instance method.
|
| 60 |
+
@pre_load(pass_many=False)
|
| 61 |
+
def remove_tag(self, item, partial, **kwargs):
|
| 62 |
+
assert partial is partial_val
|
| 63 |
+
assert "many" in kwargs
|
| 64 |
+
item["value"] = item["value"][len(self.TAG) :]
|
| 65 |
+
return item
|
| 66 |
+
|
| 67 |
+
# Explicit default raw, post load, instance method.
|
| 68 |
+
@post_load()
|
| 69 |
+
def decrement_value(self, item, partial, **kwargs):
|
| 70 |
+
assert partial is partial_val
|
| 71 |
+
assert "many" in kwargs
|
| 72 |
+
item["value"] -= 1
|
| 73 |
+
return item
|
| 74 |
+
|
| 75 |
+
schema = ExampleSchema(partial=partial_val)
|
| 76 |
+
|
| 77 |
+
# Need to re-create these because the processors will modify in place.
|
| 78 |
+
make_item = lambda: {"value": 3}
|
| 79 |
+
make_items = lambda: [make_item(), {"value": 5}]
|
| 80 |
+
|
| 81 |
+
item_dumped = schema.dump(make_item())
|
| 82 |
+
assert item_dumped == {"datum": {"value": "TAG4"}}
|
| 83 |
+
item_loaded = schema.load(item_dumped)
|
| 84 |
+
assert item_loaded == make_item()
|
| 85 |
+
|
| 86 |
+
items_dumped = schema.dump(make_items(), many=True)
|
| 87 |
+
assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]}
|
| 88 |
+
items_loaded = schema.load(items_dumped, many=True)
|
| 89 |
+
assert items_loaded == make_items()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/347
|
| 93 |
+
@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE))
|
| 94 |
+
def test_decorated_processor_returning_none(unknown):
|
| 95 |
+
class PostSchema(Schema):
|
| 96 |
+
value = fields.Integer()
|
| 97 |
+
|
| 98 |
+
@post_load
|
| 99 |
+
def load_none(self, item, **kwargs):
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
@post_dump
|
| 103 |
+
def dump_none(self, item, **kwargs):
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
class PreSchema(Schema):
|
| 107 |
+
value = fields.Integer()
|
| 108 |
+
|
| 109 |
+
@pre_load
|
| 110 |
+
def load_none(self, item, **kwargs):
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
@pre_dump
|
| 114 |
+
def dump_none(self, item, **kwargs):
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
schema = PostSchema(unknown=unknown)
|
| 118 |
+
assert schema.dump({"value": 3}) is None
|
| 119 |
+
assert schema.load({"value": 3}) is None
|
| 120 |
+
schema = PreSchema(unknown=unknown)
|
| 121 |
+
assert schema.dump({"value": 3}) == {}
|
| 122 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 123 |
+
schema.load({"value": 3})
|
| 124 |
+
assert excinfo.value.messages == {"_schema": ["Invalid input type."]}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class TestPassOriginal:
|
| 128 |
+
def test_pass_original_single(self):
|
| 129 |
+
class MySchema(Schema):
|
| 130 |
+
foo = fields.Field()
|
| 131 |
+
|
| 132 |
+
@post_load(pass_original=True)
|
| 133 |
+
def post_load(self, data, original_data, **kwargs):
|
| 134 |
+
ret = data.copy()
|
| 135 |
+
ret["_post_load"] = original_data["sentinel"]
|
| 136 |
+
return ret
|
| 137 |
+
|
| 138 |
+
@post_dump(pass_original=True)
|
| 139 |
+
def post_dump(self, data, obj, **kwargs):
|
| 140 |
+
ret = data.copy()
|
| 141 |
+
ret["_post_dump"] = obj["sentinel"]
|
| 142 |
+
return ret
|
| 143 |
+
|
| 144 |
+
schema = MySchema(unknown=EXCLUDE)
|
| 145 |
+
datum = {"foo": 42, "sentinel": 24}
|
| 146 |
+
item_loaded = schema.load(datum)
|
| 147 |
+
assert item_loaded["foo"] == 42
|
| 148 |
+
assert item_loaded["_post_load"] == 24
|
| 149 |
+
|
| 150 |
+
item_dumped = schema.dump(datum)
|
| 151 |
+
|
| 152 |
+
assert item_dumped["foo"] == 42
|
| 153 |
+
assert item_dumped["_post_dump"] == 24
|
| 154 |
+
|
| 155 |
+
def test_pass_original_many(self):
|
| 156 |
+
class MySchema(Schema):
|
| 157 |
+
foo = fields.Field()
|
| 158 |
+
|
| 159 |
+
@post_load(pass_many=True, pass_original=True)
|
| 160 |
+
def post_load(self, data, original, many, **kwargs):
|
| 161 |
+
if many:
|
| 162 |
+
ret = []
|
| 163 |
+
for item, orig_item in zip(data, original):
|
| 164 |
+
item["_post_load"] = orig_item["sentinel"]
|
| 165 |
+
ret.append(item)
|
| 166 |
+
else:
|
| 167 |
+
ret = data.copy()
|
| 168 |
+
ret["_post_load"] = original["sentinel"]
|
| 169 |
+
return ret
|
| 170 |
+
|
| 171 |
+
@post_dump(pass_many=True, pass_original=True)
|
| 172 |
+
def post_dump(self, data, original, many, **kwargs):
|
| 173 |
+
if many:
|
| 174 |
+
ret = []
|
| 175 |
+
for item, orig_item in zip(data, original):
|
| 176 |
+
item["_post_dump"] = orig_item["sentinel"]
|
| 177 |
+
ret.append(item)
|
| 178 |
+
else:
|
| 179 |
+
ret = data.copy()
|
| 180 |
+
ret["_post_dump"] = original["sentinel"]
|
| 181 |
+
return ret
|
| 182 |
+
|
| 183 |
+
schema = MySchema(unknown=EXCLUDE)
|
| 184 |
+
data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}]
|
| 185 |
+
items_loaded = schema.load(data, many=True)
|
| 186 |
+
assert items_loaded == [
|
| 187 |
+
{"foo": 42, "_post_load": 24},
|
| 188 |
+
{"foo": 424, "_post_load": 242},
|
| 189 |
+
]
|
| 190 |
+
test_values = [e["_post_load"] for e in items_loaded]
|
| 191 |
+
assert test_values == [24, 242]
|
| 192 |
+
|
| 193 |
+
items_dumped = schema.dump(data, many=True)
|
| 194 |
+
assert items_dumped == [
|
| 195 |
+
{"foo": 42, "_post_dump": 24},
|
| 196 |
+
{"foo": 424, "_post_dump": 242},
|
| 197 |
+
]
|
| 198 |
+
|
| 199 |
+
# Also check load/dump of single item
|
| 200 |
+
|
| 201 |
+
datum = {"foo": 42, "sentinel": 24}
|
| 202 |
+
item_loaded = schema.load(datum, many=False)
|
| 203 |
+
assert item_loaded == {"foo": 42, "_post_load": 24}
|
| 204 |
+
|
| 205 |
+
item_dumped = schema.dump(datum, many=False)
|
| 206 |
+
assert item_dumped == {"foo": 42, "_post_dump": 24}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def test_decorated_processor_inheritance():
|
| 210 |
+
class ParentSchema(Schema):
|
| 211 |
+
@post_dump
|
| 212 |
+
def inherited(self, item, **kwargs):
|
| 213 |
+
item["inherited"] = "inherited"
|
| 214 |
+
return item
|
| 215 |
+
|
| 216 |
+
@post_dump
|
| 217 |
+
def overridden(self, item, **kwargs):
|
| 218 |
+
item["overridden"] = "base"
|
| 219 |
+
return item
|
| 220 |
+
|
| 221 |
+
@post_dump
|
| 222 |
+
def deleted(self, item, **kwargs):
|
| 223 |
+
item["deleted"] = "retained"
|
| 224 |
+
return item
|
| 225 |
+
|
| 226 |
+
class ChildSchema(ParentSchema):
|
| 227 |
+
@post_dump
|
| 228 |
+
def overridden(self, item, **kwargs):
|
| 229 |
+
item["overridden"] = "overridden"
|
| 230 |
+
return item
|
| 231 |
+
|
| 232 |
+
deleted = None
|
| 233 |
+
|
| 234 |
+
parent_dumped = ParentSchema().dump({})
|
| 235 |
+
assert parent_dumped == {
|
| 236 |
+
"inherited": "inherited",
|
| 237 |
+
"overridden": "base",
|
| 238 |
+
"deleted": "retained",
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
child_dumped = ChildSchema().dump({})
|
| 242 |
+
assert child_dumped == {"inherited": "inherited", "overridden": "overridden"}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436
|
| 246 |
+
def test_pre_dump_is_invoked_before_implicit_field_generation():
|
| 247 |
+
class Foo(Schema):
|
| 248 |
+
field = fields.Integer()
|
| 249 |
+
|
| 250 |
+
@pre_dump
|
| 251 |
+
def hook(self, data, **kwargs):
|
| 252 |
+
data["generated_field"] = 7
|
| 253 |
+
return data
|
| 254 |
+
|
| 255 |
+
class Meta:
|
| 256 |
+
# Removing generated_field from here drops it from the output
|
| 257 |
+
fields = ("field", "generated_field")
|
| 258 |
+
|
| 259 |
+
assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7}
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class ValidatesSchema(Schema):
|
| 263 |
+
foo = fields.Int()
|
| 264 |
+
|
| 265 |
+
@validates("foo")
|
| 266 |
+
def validate_foo(self, value):
|
| 267 |
+
if value != 42:
|
| 268 |
+
raise ValidationError("The answer to life the universe and everything.")
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class TestValidatesDecorator:
|
| 272 |
+
def test_validates(self):
|
| 273 |
+
class VSchema(Schema):
|
| 274 |
+
s = fields.String()
|
| 275 |
+
|
| 276 |
+
@validates("s")
|
| 277 |
+
def validate_string(self, data):
|
| 278 |
+
raise ValidationError("nope")
|
| 279 |
+
|
| 280 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 281 |
+
VSchema().load({"s": "bar"})
|
| 282 |
+
|
| 283 |
+
assert excinfo.value.messages == {"s": ["nope"]}
|
| 284 |
+
|
| 285 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/350
|
| 286 |
+
def test_validates_with_attribute(self):
|
| 287 |
+
class S1(Schema):
|
| 288 |
+
s = fields.String(attribute="string_name")
|
| 289 |
+
|
| 290 |
+
@validates("s")
|
| 291 |
+
def validate_string(self, data):
|
| 292 |
+
raise ValidationError("nope")
|
| 293 |
+
|
| 294 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 295 |
+
S1().load({"s": "foo"})
|
| 296 |
+
assert excinfo.value.messages == {"s": ["nope"]}
|
| 297 |
+
|
| 298 |
+
with pytest.raises(ValidationError):
|
| 299 |
+
S1(many=True).load([{"s": "foo"}])
|
| 300 |
+
|
| 301 |
+
def test_validates_decorator(self):
|
| 302 |
+
schema = ValidatesSchema()
|
| 303 |
+
|
| 304 |
+
errors = schema.validate({"foo": 41})
|
| 305 |
+
assert "foo" in errors
|
| 306 |
+
assert errors["foo"][0] == "The answer to life the universe and everything."
|
| 307 |
+
|
| 308 |
+
errors = schema.validate({"foo": 42})
|
| 309 |
+
assert errors == {}
|
| 310 |
+
|
| 311 |
+
errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True)
|
| 312 |
+
assert "foo" in errors[1]
|
| 313 |
+
assert len(errors[1]["foo"]) == 1
|
| 314 |
+
assert errors[1]["foo"][0] == "The answer to life the universe and everything."
|
| 315 |
+
|
| 316 |
+
errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True)
|
| 317 |
+
assert errors == {}
|
| 318 |
+
|
| 319 |
+
errors = schema.validate({})
|
| 320 |
+
assert errors == {}
|
| 321 |
+
|
| 322 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 323 |
+
schema.load({"foo": 41})
|
| 324 |
+
errors = excinfo.value.messages
|
| 325 |
+
result = excinfo.value.valid_data
|
| 326 |
+
assert errors
|
| 327 |
+
assert result == {}
|
| 328 |
+
|
| 329 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 330 |
+
schema.load([{"foo": 42}, {"foo": 43}], many=True)
|
| 331 |
+
errors = excinfo.value.messages
|
| 332 |
+
result = excinfo.value.valid_data
|
| 333 |
+
assert len(result) == 2
|
| 334 |
+
assert result[0] == {"foo": 42}
|
| 335 |
+
assert result[1] == {}
|
| 336 |
+
assert 1 in errors
|
| 337 |
+
assert "foo" in errors[1]
|
| 338 |
+
assert errors[1]["foo"] == ["The answer to life the universe and everything."]
|
| 339 |
+
|
| 340 |
+
def test_field_not_present(self):
|
| 341 |
+
class BadSchema(ValidatesSchema):
|
| 342 |
+
@validates("bar")
|
| 343 |
+
def validate_bar(self, value):
|
| 344 |
+
raise ValidationError("Never raised.")
|
| 345 |
+
|
| 346 |
+
schema = BadSchema()
|
| 347 |
+
|
| 348 |
+
with pytest.raises(ValueError, match='"bar" field does not exist.'):
|
| 349 |
+
schema.validate({"foo": 42})
|
| 350 |
+
|
| 351 |
+
def test_precedence(self):
|
| 352 |
+
class Schema2(ValidatesSchema):
|
| 353 |
+
foo = fields.Int(validate=lambda n: n != 42)
|
| 354 |
+
bar = fields.Int(validate=lambda n: n == 1)
|
| 355 |
+
|
| 356 |
+
@validates("bar")
|
| 357 |
+
def validate_bar(self, value):
|
| 358 |
+
if value != 2:
|
| 359 |
+
raise ValidationError("Must be 2")
|
| 360 |
+
|
| 361 |
+
schema = Schema2()
|
| 362 |
+
|
| 363 |
+
errors = schema.validate({"foo": 42})
|
| 364 |
+
assert "foo" in errors
|
| 365 |
+
assert len(errors["foo"]) == 1
|
| 366 |
+
assert "Invalid value." in errors["foo"][0]
|
| 367 |
+
|
| 368 |
+
errors = schema.validate({"bar": 3})
|
| 369 |
+
assert "bar" in errors
|
| 370 |
+
assert len(errors["bar"]) == 1
|
| 371 |
+
assert "Invalid value." in errors["bar"][0]
|
| 372 |
+
|
| 373 |
+
errors = schema.validate({"bar": 1})
|
| 374 |
+
assert "bar" in errors
|
| 375 |
+
assert len(errors["bar"]) == 1
|
| 376 |
+
assert errors["bar"][0] == "Must be 2"
|
| 377 |
+
|
| 378 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/748
|
| 379 |
+
def test_validates_with_data_key(self):
|
| 380 |
+
class BadSchema(Schema):
|
| 381 |
+
foo = fields.String(data_key="foo-name")
|
| 382 |
+
|
| 383 |
+
@validates("foo")
|
| 384 |
+
def validate_string(self, data):
|
| 385 |
+
raise ValidationError("nope")
|
| 386 |
+
|
| 387 |
+
schema = BadSchema()
|
| 388 |
+
errors = schema.validate({"foo-name": "data"})
|
| 389 |
+
assert "foo-name" in errors
|
| 390 |
+
assert errors["foo-name"] == ["nope"]
|
| 391 |
+
|
| 392 |
+
schema = BadSchema()
|
| 393 |
+
errors = schema.validate(
|
| 394 |
+
[{"foo-name": "data"}, {"foo-name": "data2"}], many=True
|
| 395 |
+
)
|
| 396 |
+
assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}}
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
class TestValidatesSchemaDecorator:
|
| 400 |
+
def test_validator_nested_many_invalid_data(self):
|
| 401 |
+
class NestedSchema(Schema):
|
| 402 |
+
foo = fields.Int(required=True)
|
| 403 |
+
|
| 404 |
+
class MySchema(Schema):
|
| 405 |
+
nested = fields.Nested(NestedSchema, required=True, many=True)
|
| 406 |
+
|
| 407 |
+
schema = MySchema()
|
| 408 |
+
errors = schema.validate({"nested": [1]})
|
| 409 |
+
assert errors
|
| 410 |
+
assert "nested" in errors
|
| 411 |
+
assert 0 in errors["nested"]
|
| 412 |
+
assert errors["nested"][0] == {"_schema": ["Invalid input type."]}
|
| 413 |
+
|
| 414 |
+
def test_validator_nested_many_schema_error(self):
|
| 415 |
+
class NestedSchema(Schema):
|
| 416 |
+
foo = fields.Int(required=True)
|
| 417 |
+
|
| 418 |
+
@validates_schema
|
| 419 |
+
def validate_schema(self, data, **kwargs):
|
| 420 |
+
raise ValidationError("This will never work.")
|
| 421 |
+
|
| 422 |
+
class MySchema(Schema):
|
| 423 |
+
nested = fields.Nested(NestedSchema, required=True, many=True)
|
| 424 |
+
|
| 425 |
+
schema = MySchema()
|
| 426 |
+
errors = schema.validate({"nested": [{"foo": 1}]})
|
| 427 |
+
assert errors
|
| 428 |
+
assert "nested" in errors
|
| 429 |
+
assert 0 in errors["nested"]
|
| 430 |
+
assert errors["nested"][0] == {"_schema": ["This will never work."]}
|
| 431 |
+
|
| 432 |
+
def test_validator_nested_many_field_error(self):
|
| 433 |
+
class NestedSchema(Schema):
|
| 434 |
+
foo = fields.Int(required=True)
|
| 435 |
+
|
| 436 |
+
@validates_schema
|
| 437 |
+
def validate_schema(self, data, **kwargs):
|
| 438 |
+
raise ValidationError("This will never work.", "foo")
|
| 439 |
+
|
| 440 |
+
class MySchema(Schema):
|
| 441 |
+
nested = fields.Nested(NestedSchema, required=True, many=True)
|
| 442 |
+
|
| 443 |
+
schema = MySchema()
|
| 444 |
+
errors = schema.validate({"nested": [{"foo": 1}]})
|
| 445 |
+
assert errors
|
| 446 |
+
assert "nested" in errors
|
| 447 |
+
assert 0 in errors["nested"]
|
| 448 |
+
assert errors["nested"][0] == {"foo": ["This will never work."]}
|
| 449 |
+
|
| 450 |
+
@pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],))
|
| 451 |
+
@pytest.mark.parametrize(
|
| 452 |
+
"pass_many,expected_data,expected_original_data",
|
| 453 |
+
(
|
| 454 |
+
[True, [{"foo": 1}], [{"foo": 1, "bar": 2}]],
|
| 455 |
+
[False, {"foo": 1}, {"foo": 1, "bar": 2}],
|
| 456 |
+
),
|
| 457 |
+
)
|
| 458 |
+
def test_validator_nested_many_pass_original_and_pass_many(
|
| 459 |
+
self, pass_many, data, expected_data, expected_original_data
|
| 460 |
+
):
|
| 461 |
+
class NestedSchema(Schema):
|
| 462 |
+
foo = fields.Int(required=True)
|
| 463 |
+
|
| 464 |
+
@validates_schema(pass_many=pass_many, pass_original=True)
|
| 465 |
+
def validate_schema(self, data, original_data, many, **kwargs):
|
| 466 |
+
assert data == expected_data
|
| 467 |
+
assert original_data == expected_original_data
|
| 468 |
+
assert many is True
|
| 469 |
+
raise ValidationError("Method called")
|
| 470 |
+
|
| 471 |
+
class MySchema(Schema):
|
| 472 |
+
nested = fields.Nested(
|
| 473 |
+
NestedSchema, required=True, many=True, unknown=EXCLUDE
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
schema = MySchema()
|
| 477 |
+
errors = schema.validate({"nested": data})
|
| 478 |
+
error = errors["nested"] if pass_many else errors["nested"][0]
|
| 479 |
+
assert error["_schema"][0] == "Method called"
|
| 480 |
+
|
| 481 |
+
def test_decorated_validators(self):
|
| 482 |
+
class MySchema(Schema):
|
| 483 |
+
foo = fields.Int()
|
| 484 |
+
bar = fields.Int()
|
| 485 |
+
|
| 486 |
+
@validates_schema
|
| 487 |
+
def validate_schema(self, data, **kwargs):
|
| 488 |
+
if data["foo"] <= 3:
|
| 489 |
+
raise ValidationError("Must be greater than 3")
|
| 490 |
+
|
| 491 |
+
@validates_schema(pass_many=True)
|
| 492 |
+
def validate_raw(self, data, many, **kwargs):
|
| 493 |
+
if many:
|
| 494 |
+
assert type(data) is list
|
| 495 |
+
if len(data) < 2:
|
| 496 |
+
raise ValidationError("Must provide at least 2 items")
|
| 497 |
+
|
| 498 |
+
@validates_schema
|
| 499 |
+
def validate_bar(self, data, **kwargs):
|
| 500 |
+
if "bar" in data and data["bar"] < 0:
|
| 501 |
+
raise ValidationError("bar must not be negative", "bar")
|
| 502 |
+
|
| 503 |
+
schema = MySchema()
|
| 504 |
+
errors = schema.validate({"foo": 3})
|
| 505 |
+
assert "_schema" in errors
|
| 506 |
+
assert errors["_schema"][0] == "Must be greater than 3"
|
| 507 |
+
|
| 508 |
+
errors = schema.validate([{"foo": 4}], many=True)
|
| 509 |
+
assert "_schema" in errors
|
| 510 |
+
assert len(errors["_schema"]) == 1
|
| 511 |
+
assert errors["_schema"][0] == "Must provide at least 2 items"
|
| 512 |
+
|
| 513 |
+
errors = schema.validate({"foo": 4, "bar": -1})
|
| 514 |
+
assert "bar" in errors
|
| 515 |
+
assert len(errors["bar"]) == 1
|
| 516 |
+
assert errors["bar"][0] == "bar must not be negative"
|
| 517 |
+
|
| 518 |
+
def test_multiple_validators(self):
|
| 519 |
+
class MySchema(Schema):
|
| 520 |
+
foo = fields.Int()
|
| 521 |
+
bar = fields.Int()
|
| 522 |
+
|
| 523 |
+
@validates_schema
|
| 524 |
+
def validate_schema(self, data, **kwargs):
|
| 525 |
+
if data["foo"] <= 3:
|
| 526 |
+
raise ValidationError("Must be greater than 3")
|
| 527 |
+
|
| 528 |
+
@validates_schema
|
| 529 |
+
def validate_bar(self, data, **kwargs):
|
| 530 |
+
if "bar" in data and data["bar"] < 0:
|
| 531 |
+
raise ValidationError("bar must not be negative")
|
| 532 |
+
|
| 533 |
+
schema = MySchema()
|
| 534 |
+
errors = schema.validate({"foo": 3, "bar": -1})
|
| 535 |
+
assert type(errors) is dict
|
| 536 |
+
assert "_schema" in errors
|
| 537 |
+
assert len(errors["_schema"]) == 2
|
| 538 |
+
assert "Must be greater than 3" in errors["_schema"]
|
| 539 |
+
assert "bar must not be negative" in errors["_schema"]
|
| 540 |
+
|
| 541 |
+
errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True)
|
| 542 |
+
assert type(errors) is dict
|
| 543 |
+
assert "_schema" in errors[0]
|
| 544 |
+
assert len(errors[0]["_schema"]) == 2
|
| 545 |
+
assert "Must be greater than 3" in errors[0]["_schema"]
|
| 546 |
+
assert "bar must not be negative" in errors[0]["_schema"]
|
| 547 |
+
assert len(errors[1]["_schema"]) == 1
|
| 548 |
+
assert "Must be greater than 3" in errors[0]["_schema"]
|
| 549 |
+
|
| 550 |
+
def test_multiple_validators_merge_dict_errors(self):
|
| 551 |
+
class NestedSchema(Schema):
|
| 552 |
+
foo = fields.Int()
|
| 553 |
+
bar = fields.Int()
|
| 554 |
+
|
| 555 |
+
class MySchema(Schema):
|
| 556 |
+
nested = fields.Nested(NestedSchema)
|
| 557 |
+
|
| 558 |
+
@validates_schema
|
| 559 |
+
def validate_nested_foo(self, data, **kwargs):
|
| 560 |
+
raise ValidationError({"nested": {"foo": ["Invalid foo"]}})
|
| 561 |
+
|
| 562 |
+
@validates_schema
|
| 563 |
+
def validate_nested_bar_1(self, data, **kwargs):
|
| 564 |
+
raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}})
|
| 565 |
+
|
| 566 |
+
@validates_schema
|
| 567 |
+
def validate_nested_bar_2(self, data, **kwargs):
|
| 568 |
+
raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}})
|
| 569 |
+
|
| 570 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 571 |
+
MySchema().load({"nested": {"foo": 1, "bar": 2}})
|
| 572 |
+
|
| 573 |
+
assert excinfo.value.messages == {
|
| 574 |
+
"nested": {
|
| 575 |
+
"foo": ["Invalid foo"],
|
| 576 |
+
"bar": ["Invalid bar 1", "Invalid bar 2"],
|
| 577 |
+
}
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
def test_passing_original_data(self):
|
| 581 |
+
class MySchema(Schema):
|
| 582 |
+
foo = fields.Int()
|
| 583 |
+
bar = fields.Int()
|
| 584 |
+
|
| 585 |
+
@validates_schema(pass_original=True)
|
| 586 |
+
def validate_original(self, data, original_data, partial, **kwargs):
|
| 587 |
+
if isinstance(original_data, dict) and isinstance(
|
| 588 |
+
original_data["foo"], str
|
| 589 |
+
):
|
| 590 |
+
raise ValidationError("foo cannot be a string")
|
| 591 |
+
|
| 592 |
+
@validates_schema(pass_many=True, pass_original=True)
|
| 593 |
+
def validate_original_bar(self, data, original_data, many, **kwargs):
|
| 594 |
+
def check(datum):
|
| 595 |
+
if isinstance(datum, dict) and isinstance(datum["bar"], str):
|
| 596 |
+
raise ValidationError("bar cannot be a string")
|
| 597 |
+
|
| 598 |
+
if many:
|
| 599 |
+
for each in original_data:
|
| 600 |
+
check(each)
|
| 601 |
+
else:
|
| 602 |
+
check(original_data)
|
| 603 |
+
|
| 604 |
+
schema = MySchema()
|
| 605 |
+
|
| 606 |
+
errors = schema.validate({"foo": "4", "bar": 12})
|
| 607 |
+
assert errors["_schema"] == ["foo cannot be a string"]
|
| 608 |
+
|
| 609 |
+
errors = schema.validate({"foo": 4, "bar": "42"})
|
| 610 |
+
assert errors["_schema"] == ["bar cannot be a string"]
|
| 611 |
+
|
| 612 |
+
errors = schema.validate([{"foo": 4, "bar": "42"}], many=True)
|
| 613 |
+
assert errors["_schema"] == ["bar cannot be a string"]
|
| 614 |
+
|
| 615 |
+
def test_allow_reporting_field_errors_in_schema_validator(self):
|
| 616 |
+
class NestedSchema(Schema):
|
| 617 |
+
baz = fields.Int(required=True)
|
| 618 |
+
|
| 619 |
+
class MySchema(Schema):
|
| 620 |
+
foo = fields.Int(required=True)
|
| 621 |
+
bar = fields.Nested(NestedSchema, required=True)
|
| 622 |
+
bam = fields.Int(required=True)
|
| 623 |
+
|
| 624 |
+
@validates_schema(skip_on_field_errors=True)
|
| 625 |
+
def consistency_validation(self, data, **kwargs):
|
| 626 |
+
errors = {}
|
| 627 |
+
if data["bar"]["baz"] != data["foo"]:
|
| 628 |
+
errors["bar"] = {"baz": "Non-matching value"}
|
| 629 |
+
if data["bam"] > data["foo"]:
|
| 630 |
+
errors["bam"] = "Value should be less than foo"
|
| 631 |
+
if errors:
|
| 632 |
+
raise ValidationError(errors)
|
| 633 |
+
|
| 634 |
+
schema = MySchema()
|
| 635 |
+
errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6})
|
| 636 |
+
assert errors["bar"]["baz"] == "Non-matching value"
|
| 637 |
+
assert errors["bam"] == "Value should be less than foo"
|
| 638 |
+
|
| 639 |
+
# https://github.com/marshmallow-code/marshmallow/issues/273
|
| 640 |
+
def test_allow_arbitrary_field_names_in_error(self):
|
| 641 |
+
class MySchema(Schema):
|
| 642 |
+
@validates_schema
|
| 643 |
+
def validator(self, data, **kwargs):
|
| 644 |
+
raise ValidationError("Error message", "arbitrary_key")
|
| 645 |
+
|
| 646 |
+
errors = MySchema().validate({})
|
| 647 |
+
assert errors["arbitrary_key"] == ["Error message"]
|
| 648 |
+
|
| 649 |
+
def test_skip_on_field_errors(self):
|
| 650 |
+
class MySchema(Schema):
|
| 651 |
+
foo = fields.Int(required=True, validate=lambda n: n == 3)
|
| 652 |
+
bar = fields.Int(required=True)
|
| 653 |
+
|
| 654 |
+
@validates_schema(skip_on_field_errors=True)
|
| 655 |
+
def validate_schema(self, data, **kwargs):
|
| 656 |
+
if data["foo"] != data["bar"]:
|
| 657 |
+
raise ValidationError("Foo and bar must be equal.")
|
| 658 |
+
|
| 659 |
+
@validates_schema(skip_on_field_errors=True, pass_many=True)
|
| 660 |
+
def validate_many(self, data, many, **kwargs):
|
| 661 |
+
if many:
|
| 662 |
+
assert type(data) is list
|
| 663 |
+
if len(data) < 2:
|
| 664 |
+
raise ValidationError("Must provide at least 2 items")
|
| 665 |
+
|
| 666 |
+
schema = MySchema()
|
| 667 |
+
# check that schema errors still occur with no field errors
|
| 668 |
+
errors = schema.validate({"foo": 3, "bar": 4})
|
| 669 |
+
assert "_schema" in errors
|
| 670 |
+
assert errors["_schema"][0] == "Foo and bar must be equal."
|
| 671 |
+
|
| 672 |
+
errors = schema.validate([{"foo": 3, "bar": 3}], many=True)
|
| 673 |
+
assert "_schema" in errors
|
| 674 |
+
assert errors["_schema"][0] == "Must provide at least 2 items"
|
| 675 |
+
|
| 676 |
+
# check that schema errors don't occur when field errors do
|
| 677 |
+
errors = schema.validate({"foo": 3, "bar": "not an int"})
|
| 678 |
+
assert "bar" in errors
|
| 679 |
+
assert "_schema" not in errors
|
| 680 |
+
|
| 681 |
+
errors = schema.validate({"foo": 2, "bar": 2})
|
| 682 |
+
assert "foo" in errors
|
| 683 |
+
assert "_schema" not in errors
|
| 684 |
+
|
| 685 |
+
errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True)
|
| 686 |
+
assert "bar" in errors[0]
|
| 687 |
+
assert "_schema" not in errors
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def test_decorator_error_handling(): # noqa: C901
|
| 691 |
+
class ExampleSchema(Schema):
|
| 692 |
+
foo = fields.Int()
|
| 693 |
+
bar = fields.Int()
|
| 694 |
+
|
| 695 |
+
@pre_load()
|
| 696 |
+
def pre_load_error1(self, item, **kwargs):
|
| 697 |
+
if item["foo"] != 0:
|
| 698 |
+
return item
|
| 699 |
+
errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]}
|
| 700 |
+
raise ValidationError(errors)
|
| 701 |
+
|
| 702 |
+
@pre_load()
|
| 703 |
+
def pre_load_error2(self, item, **kwargs):
|
| 704 |
+
if item["foo"] != 4:
|
| 705 |
+
return item
|
| 706 |
+
raise ValidationError("preloadmsg1", "foo")
|
| 707 |
+
|
| 708 |
+
@pre_load()
|
| 709 |
+
def pre_load_error3(self, item, **kwargs):
|
| 710 |
+
if item["foo"] != 8:
|
| 711 |
+
return item
|
| 712 |
+
raise ValidationError("preloadmsg1")
|
| 713 |
+
|
| 714 |
+
@post_load()
|
| 715 |
+
def post_load_error1(self, item, **kwargs):
|
| 716 |
+
if item["foo"] != 1:
|
| 717 |
+
return item
|
| 718 |
+
errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]}
|
| 719 |
+
raise ValidationError(errors)
|
| 720 |
+
|
| 721 |
+
@post_load()
|
| 722 |
+
def post_load_error2(self, item, **kwargs):
|
| 723 |
+
if item["foo"] != 5:
|
| 724 |
+
return item
|
| 725 |
+
raise ValidationError("postloadmsg1", "foo")
|
| 726 |
+
|
| 727 |
+
def make_item(foo, bar):
|
| 728 |
+
data = schema.load({"foo": foo, "bar": bar})
|
| 729 |
+
assert data is not None
|
| 730 |
+
return data
|
| 731 |
+
|
| 732 |
+
schema = ExampleSchema()
|
| 733 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 734 |
+
schema.load({"foo": 0, "bar": 1})
|
| 735 |
+
errors = excinfo.value.messages
|
| 736 |
+
assert "foo" in errors
|
| 737 |
+
assert len(errors["foo"]) == 1
|
| 738 |
+
assert errors["foo"][0] == "preloadmsg1"
|
| 739 |
+
assert "bar" in errors
|
| 740 |
+
assert len(errors["bar"]) == 2
|
| 741 |
+
assert "preloadmsg2" in errors["bar"]
|
| 742 |
+
assert "preloadmsg3" in errors["bar"]
|
| 743 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 744 |
+
schema.load({"foo": 1, "bar": 1})
|
| 745 |
+
errors = excinfo.value.messages
|
| 746 |
+
assert "foo" in errors
|
| 747 |
+
assert len(errors["foo"]) == 1
|
| 748 |
+
assert errors["foo"][0] == "postloadmsg1"
|
| 749 |
+
assert "bar" in errors
|
| 750 |
+
assert len(errors["bar"]) == 2
|
| 751 |
+
assert "postloadmsg2" in errors["bar"]
|
| 752 |
+
assert "postloadmsg3" in errors["bar"]
|
| 753 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 754 |
+
schema.load({"foo": 4, "bar": 1})
|
| 755 |
+
errors = excinfo.value.messages
|
| 756 |
+
assert len(errors) == 1
|
| 757 |
+
assert "foo" in errors
|
| 758 |
+
assert len(errors["foo"]) == 1
|
| 759 |
+
assert errors["foo"][0] == "preloadmsg1"
|
| 760 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 761 |
+
schema.load({"foo": 5, "bar": 1})
|
| 762 |
+
errors = excinfo.value.messages
|
| 763 |
+
assert len(errors) == 1
|
| 764 |
+
assert "foo" in errors
|
| 765 |
+
assert len(errors["foo"]) == 1
|
| 766 |
+
assert errors["foo"][0] == "postloadmsg1"
|
| 767 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 768 |
+
schema.load({"foo": 8, "bar": 1})
|
| 769 |
+
errors = excinfo.value.messages
|
| 770 |
+
assert len(errors) == 1
|
| 771 |
+
assert "_schema" in errors
|
| 772 |
+
assert len(errors["_schema"]) == 1
|
| 773 |
+
assert errors["_schema"][0] == "preloadmsg1"
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
@pytest.mark.parametrize("decorator", [pre_load, post_load])
|
| 777 |
+
def test_decorator_error_handling_with_load(decorator):
|
| 778 |
+
class ExampleSchema(Schema):
|
| 779 |
+
@decorator
|
| 780 |
+
def raise_value_error(self, item, **kwargs):
|
| 781 |
+
raise ValidationError({"foo": "error"})
|
| 782 |
+
|
| 783 |
+
schema = ExampleSchema()
|
| 784 |
+
with pytest.raises(ValidationError) as exc:
|
| 785 |
+
schema.load({})
|
| 786 |
+
assert exc.value.messages == {"foo": "error"}
|
| 787 |
+
schema.dump(object())
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
@pytest.mark.parametrize("decorator", [pre_load, post_load])
|
| 791 |
+
def test_decorator_error_handling_with_load_dict_error(decorator):
|
| 792 |
+
class ExampleSchema(Schema):
|
| 793 |
+
@decorator
|
| 794 |
+
def raise_value_error(self, item, **kwargs):
|
| 795 |
+
raise ValidationError({"foo": "error"}, "nested_field")
|
| 796 |
+
|
| 797 |
+
schema = ExampleSchema()
|
| 798 |
+
with pytest.raises(ValidationError) as exc:
|
| 799 |
+
schema.load({})
|
| 800 |
+
assert exc.value.messages == {"nested_field": {"foo": "error"}}
|
| 801 |
+
schema.dump(object())
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
@pytest.mark.parametrize("decorator", [pre_dump, post_dump])
|
| 805 |
+
def test_decorator_error_handling_with_dump(decorator):
|
| 806 |
+
class ExampleSchema(Schema):
|
| 807 |
+
@decorator
|
| 808 |
+
def raise_value_error(self, item, **kwargs):
|
| 809 |
+
raise ValidationError({"foo": "error"})
|
| 810 |
+
|
| 811 |
+
schema = ExampleSchema()
|
| 812 |
+
with pytest.raises(ValidationError) as exc:
|
| 813 |
+
schema.dump(object())
|
| 814 |
+
assert exc.value.messages == {"foo": "error"}
|
| 815 |
+
schema.load({})
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
class Nested:
|
| 819 |
+
def __init__(self, foo):
|
| 820 |
+
self.foo = foo
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
class Example:
|
| 824 |
+
def __init__(self, nested):
|
| 825 |
+
self.nested = nested
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
example = Example(nested=[Nested(x) for x in range(1)])
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
@pytest.mark.parametrize(
|
| 832 |
+
"data,expected_data,expected_original_data",
|
| 833 |
+
([example, {"foo": 0}, example.nested[0]],),
|
| 834 |
+
)
|
| 835 |
+
def test_decorator_post_dump_with_nested_original_and_pass_many(
|
| 836 |
+
data, expected_data, expected_original_data
|
| 837 |
+
):
|
| 838 |
+
class NestedSchema(Schema):
|
| 839 |
+
foo = fields.Int(required=True)
|
| 840 |
+
|
| 841 |
+
@post_dump(pass_many=False, pass_original=True)
|
| 842 |
+
def check_pass_original_when_pass_many_false(
|
| 843 |
+
self, data, original_data, **kwargs
|
| 844 |
+
):
|
| 845 |
+
assert data == expected_data
|
| 846 |
+
assert original_data == expected_original_data
|
| 847 |
+
return data
|
| 848 |
+
|
| 849 |
+
@post_dump(pass_many=True, pass_original=True)
|
| 850 |
+
def check_pass_original_when_pass_many_true(
|
| 851 |
+
self, data, original_data, many, **kwargs
|
| 852 |
+
):
|
| 853 |
+
assert many is True
|
| 854 |
+
assert data == [expected_data]
|
| 855 |
+
assert original_data == [expected_original_data]
|
| 856 |
+
return data
|
| 857 |
+
|
| 858 |
+
class ExampleSchema(Schema):
|
| 859 |
+
nested = fields.Nested(NestedSchema, required=True, many=True)
|
| 860 |
+
|
| 861 |
+
schema = ExampleSchema()
|
| 862 |
+
assert schema.dump(data) == {"nested": [{"foo": 0}]}
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
@pytest.mark.parametrize(
|
| 866 |
+
"data,expected_data,expected_original_data",
|
| 867 |
+
([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],),
|
| 868 |
+
)
|
| 869 |
+
def test_decorator_post_load_with_nested_original_and_pass_many(
|
| 870 |
+
data, expected_data, expected_original_data
|
| 871 |
+
):
|
| 872 |
+
class NestedSchema(Schema):
|
| 873 |
+
foo = fields.Int(required=True)
|
| 874 |
+
|
| 875 |
+
@post_load(pass_many=False, pass_original=True)
|
| 876 |
+
def check_pass_original_when_pass_many_false(
|
| 877 |
+
self, data, original_data, **kwargs
|
| 878 |
+
):
|
| 879 |
+
assert data == expected_data
|
| 880 |
+
assert original_data == expected_original_data
|
| 881 |
+
return data
|
| 882 |
+
|
| 883 |
+
@post_load(pass_many=True, pass_original=True)
|
| 884 |
+
def check_pass_original_when_pass_many_true(
|
| 885 |
+
self, data, original_data, many, **kwargs
|
| 886 |
+
):
|
| 887 |
+
assert many is True
|
| 888 |
+
assert data == [expected_data]
|
| 889 |
+
assert original_data == [expected_original_data]
|
| 890 |
+
return data
|
| 891 |
+
|
| 892 |
+
class ExampleSchema(Schema):
|
| 893 |
+
nested = fields.Nested(NestedSchema, required=True, many=True)
|
| 894 |
+
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime as dt
|
| 2 |
+
import decimal
|
| 3 |
+
import ipaddress
|
| 4 |
+
import math
|
| 5 |
+
import uuid
|
| 6 |
+
from unittest.mock import patch
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate
|
| 11 |
+
from marshmallow.exceptions import ValidationError
|
| 12 |
+
from marshmallow.validate import Equal
|
| 13 |
+
from tests.base import (
|
| 14 |
+
ALL_FIELDS,
|
| 15 |
+
DateEnum,
|
| 16 |
+
GenderEnum,
|
| 17 |
+
HairColorEnum,
|
| 18 |
+
assert_date_equal,
|
| 19 |
+
assert_time_equal,
|
| 20 |
+
central,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class MockDateTimeOverflowError(dt.datetime):
|
| 25 |
+
"""Used to simulate the possible OverflowError of datetime.fromtimestamp"""
|
| 26 |
+
|
| 27 |
+
def fromtimestamp(self, *args, **kwargs):
|
| 28 |
+
raise OverflowError()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class MockDateTimeOSError(dt.datetime):
|
| 32 |
+
"""Used to simulate the possible OSError of datetime.fromtimestamp"""
|
| 33 |
+
|
| 34 |
+
def fromtimestamp(self, *args, **kwargs):
|
| 35 |
+
raise OSError()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestDeserializingNone:
|
| 39 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 40 |
+
def test_fields_allow_none_deserialize_to_none(self, FieldClass):
|
| 41 |
+
field = FieldClass(allow_none=True)
|
| 42 |
+
assert field.deserialize(None) is None
|
| 43 |
+
|
| 44 |
+
# https://github.com/marshmallow-code/marshmallow/issues/111
|
| 45 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 46 |
+
def test_fields_dont_allow_none_by_default(self, FieldClass):
|
| 47 |
+
field = FieldClass()
|
| 48 |
+
with pytest.raises(ValidationError, match="Field may not be null."):
|
| 49 |
+
field.deserialize(None)
|
| 50 |
+
|
| 51 |
+
def test_allow_none_is_true_if_missing_is_true(self):
|
| 52 |
+
field = fields.Field(load_default=None)
|
| 53 |
+
assert field.allow_none is True
|
| 54 |
+
assert field.deserialize(None) is None
|
| 55 |
+
|
| 56 |
+
def test_list_field_deserialize_none_to_none(self):
|
| 57 |
+
field = fields.List(fields.String(allow_none=True), allow_none=True)
|
| 58 |
+
assert field.deserialize(None) is None
|
| 59 |
+
|
| 60 |
+
def test_tuple_field_deserialize_none_to_none(self):
|
| 61 |
+
field = fields.Tuple([fields.String()], allow_none=True)
|
| 62 |
+
assert field.deserialize(None) is None
|
| 63 |
+
|
| 64 |
+
def test_list_of_nested_allow_none_deserialize_none_to_none(self):
|
| 65 |
+
field = fields.List(fields.Nested(Schema(), allow_none=True))
|
| 66 |
+
assert field.deserialize([None]) == [None]
|
| 67 |
+
|
| 68 |
+
def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self):
|
| 69 |
+
field = fields.List(fields.Nested(Schema(), allow_none=False))
|
| 70 |
+
with pytest.raises(ValidationError):
|
| 71 |
+
field.deserialize([None])
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class TestFieldDeserialization:
|
| 75 |
+
def test_float_field_deserialization(self):
|
| 76 |
+
field = fields.Float()
|
| 77 |
+
assert math.isclose(field.deserialize("12.3"), 12.3)
|
| 78 |
+
assert math.isclose(field.deserialize(12.3), 12.3)
|
| 79 |
+
|
| 80 |
+
@pytest.mark.parametrize("in_val", ["bad", "", {}, True, False])
|
| 81 |
+
def test_invalid_float_field_deserialization(self, in_val):
|
| 82 |
+
field = fields.Float()
|
| 83 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 84 |
+
field.deserialize(in_val)
|
| 85 |
+
assert excinfo.value.args[0] == "Not a valid number."
|
| 86 |
+
|
| 87 |
+
def test_float_field_overflow(self):
|
| 88 |
+
field = fields.Float()
|
| 89 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 90 |
+
field.deserialize(2**1024)
|
| 91 |
+
assert excinfo.value.args[0] == "Number too large."
|
| 92 |
+
|
| 93 |
+
def test_integer_field_deserialization(self):
|
| 94 |
+
field = fields.Integer()
|
| 95 |
+
assert field.deserialize("42") == 42
|
| 96 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 97 |
+
field.deserialize("42.0")
|
| 98 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 99 |
+
with pytest.raises(ValidationError):
|
| 100 |
+
field.deserialize("bad")
|
| 101 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 102 |
+
with pytest.raises(ValidationError):
|
| 103 |
+
field.deserialize({})
|
| 104 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 105 |
+
|
| 106 |
+
def test_strict_integer_field_deserialization(self):
|
| 107 |
+
field = fields.Integer(strict=True)
|
| 108 |
+
assert field.deserialize(42) == 42
|
| 109 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 110 |
+
field.deserialize(42.0)
|
| 111 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 112 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 113 |
+
field.deserialize(decimal.Decimal("42.0"))
|
| 114 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 115 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 116 |
+
field.deserialize("42")
|
| 117 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 118 |
+
|
| 119 |
+
def test_decimal_field_deserialization(self):
|
| 120 |
+
m1 = 12
|
| 121 |
+
m2 = "12.355"
|
| 122 |
+
m3 = decimal.Decimal(1)
|
| 123 |
+
m4 = 3.14
|
| 124 |
+
m5 = "abc"
|
| 125 |
+
m6 = [1, 2]
|
| 126 |
+
|
| 127 |
+
field = fields.Decimal()
|
| 128 |
+
assert isinstance(field.deserialize(m1), decimal.Decimal)
|
| 129 |
+
assert field.deserialize(m1) == decimal.Decimal(12)
|
| 130 |
+
assert isinstance(field.deserialize(m2), decimal.Decimal)
|
| 131 |
+
assert field.deserialize(m2) == decimal.Decimal("12.355")
|
| 132 |
+
assert isinstance(field.deserialize(m3), decimal.Decimal)
|
| 133 |
+
assert field.deserialize(m3) == decimal.Decimal(1)
|
| 134 |
+
assert isinstance(field.deserialize(m4), decimal.Decimal)
|
| 135 |
+
assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2)
|
| 136 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 137 |
+
field.deserialize(m5)
|
| 138 |
+
assert excinfo.value.args[0] == "Not a valid number."
|
| 139 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 140 |
+
field.deserialize(m6)
|
| 141 |
+
assert excinfo.value.args[0] == "Not a valid number."
|
| 142 |
+
|
| 143 |
+
def test_decimal_field_with_places(self):
|
| 144 |
+
m1 = 12
|
| 145 |
+
m2 = "12.355"
|
| 146 |
+
m3 = decimal.Decimal(1)
|
| 147 |
+
m4 = "abc"
|
| 148 |
+
m5 = [1, 2]
|
| 149 |
+
|
| 150 |
+
field = fields.Decimal(1)
|
| 151 |
+
assert isinstance(field.deserialize(m1), decimal.Decimal)
|
| 152 |
+
assert field.deserialize(m1) == decimal.Decimal(12)
|
| 153 |
+
assert isinstance(field.deserialize(m2), decimal.Decimal)
|
| 154 |
+
assert field.deserialize(m2) == decimal.Decimal("12.4")
|
| 155 |
+
assert isinstance(field.deserialize(m3), decimal.Decimal)
|
| 156 |
+
assert field.deserialize(m3) == decimal.Decimal(1)
|
| 157 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 158 |
+
field.deserialize(m4)
|
| 159 |
+
assert excinfo.value.args[0] == "Not a valid number."
|
| 160 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 161 |
+
field.deserialize(m5)
|
| 162 |
+
assert excinfo.value.args[0] == "Not a valid number."
|
| 163 |
+
|
| 164 |
+
def test_decimal_field_with_places_and_rounding(self):
|
| 165 |
+
m1 = 12
|
| 166 |
+
m2 = "12.355"
|
| 167 |
+
m3 = decimal.Decimal(1)
|
| 168 |
+
m4 = "abc"
|
| 169 |
+
m5 = [1, 2]
|
| 170 |
+
|
| 171 |
+
field = fields.Decimal(1, decimal.ROUND_DOWN)
|
| 172 |
+
assert isinstance(field.deserialize(m1), decimal.Decimal)
|
| 173 |
+
assert field.deserialize(m1) == decimal.Decimal(12)
|
| 174 |
+
assert isinstance(field.deserialize(m2), decimal.Decimal)
|
| 175 |
+
assert field.deserialize(m2) == decimal.Decimal("12.3")
|
| 176 |
+
assert isinstance(field.deserialize(m3), decimal.Decimal)
|
| 177 |
+
assert field.deserialize(m3) == decimal.Decimal(1)
|
| 178 |
+
with pytest.raises(ValidationError):
|
| 179 |
+
field.deserialize(m4)
|
| 180 |
+
with pytest.raises(ValidationError):
|
| 181 |
+
field.deserialize(m5)
|
| 182 |
+
|
| 183 |
+
def test_decimal_field_deserialization_string(self):
|
| 184 |
+
m1 = 12
|
| 185 |
+
m2 = "12.355"
|
| 186 |
+
m3 = decimal.Decimal(1)
|
| 187 |
+
m4 = "abc"
|
| 188 |
+
m5 = [1, 2]
|
| 189 |
+
|
| 190 |
+
field = fields.Decimal(as_string=True)
|
| 191 |
+
assert isinstance(field.deserialize(m1), decimal.Decimal)
|
| 192 |
+
assert field.deserialize(m1) == decimal.Decimal(12)
|
| 193 |
+
assert isinstance(field.deserialize(m2), decimal.Decimal)
|
| 194 |
+
assert field.deserialize(m2) == decimal.Decimal("12.355")
|
| 195 |
+
assert isinstance(field.deserialize(m3), decimal.Decimal)
|
| 196 |
+
assert field.deserialize(m3) == decimal.Decimal(1)
|
| 197 |
+
with pytest.raises(ValidationError):
|
| 198 |
+
field.deserialize(m4)
|
| 199 |
+
with pytest.raises(ValidationError):
|
| 200 |
+
field.deserialize(m5)
|
| 201 |
+
|
| 202 |
+
def test_decimal_field_special_values(self):
|
| 203 |
+
m1 = "-NaN"
|
| 204 |
+
m2 = "NaN"
|
| 205 |
+
m3 = "-sNaN"
|
| 206 |
+
m4 = "sNaN"
|
| 207 |
+
m5 = "-Infinity"
|
| 208 |
+
m6 = "Infinity"
|
| 209 |
+
m7 = "-0"
|
| 210 |
+
|
| 211 |
+
field = fields.Decimal(places=2, allow_nan=True)
|
| 212 |
+
|
| 213 |
+
m1d = field.deserialize(m1)
|
| 214 |
+
assert isinstance(m1d, decimal.Decimal)
|
| 215 |
+
assert m1d.is_qnan() and not m1d.is_signed()
|
| 216 |
+
|
| 217 |
+
m2d = field.deserialize(m2)
|
| 218 |
+
assert isinstance(m2d, decimal.Decimal)
|
| 219 |
+
assert m2d.is_qnan() and not m2d.is_signed()
|
| 220 |
+
|
| 221 |
+
m3d = field.deserialize(m3)
|
| 222 |
+
assert isinstance(m3d, decimal.Decimal)
|
| 223 |
+
assert m3d.is_qnan() and not m3d.is_signed()
|
| 224 |
+
|
| 225 |
+
m4d = field.deserialize(m4)
|
| 226 |
+
assert isinstance(m4d, decimal.Decimal)
|
| 227 |
+
assert m4d.is_qnan() and not m4d.is_signed()
|
| 228 |
+
|
| 229 |
+
m5d = field.deserialize(m5)
|
| 230 |
+
assert isinstance(m5d, decimal.Decimal)
|
| 231 |
+
assert m5d.is_infinite() and m5d.is_signed()
|
| 232 |
+
|
| 233 |
+
m6d = field.deserialize(m6)
|
| 234 |
+
assert isinstance(m6d, decimal.Decimal)
|
| 235 |
+
assert m6d.is_infinite() and not m6d.is_signed()
|
| 236 |
+
|
| 237 |
+
m7d = field.deserialize(m7)
|
| 238 |
+
assert isinstance(m7d, decimal.Decimal)
|
| 239 |
+
assert m7d.is_zero() and m7d.is_signed()
|
| 240 |
+
|
| 241 |
+
def test_decimal_field_special_values_not_permitted(self):
|
| 242 |
+
m1 = "-NaN"
|
| 243 |
+
m2 = "NaN"
|
| 244 |
+
m3 = "-sNaN"
|
| 245 |
+
m4 = "sNaN"
|
| 246 |
+
m5 = "-Infinity"
|
| 247 |
+
m6 = "Infinity"
|
| 248 |
+
m7 = "-0"
|
| 249 |
+
|
| 250 |
+
field = fields.Decimal(places=2)
|
| 251 |
+
|
| 252 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 253 |
+
field.deserialize(m1)
|
| 254 |
+
assert str(excinfo.value.args[0]) == (
|
| 255 |
+
"Special numeric values (nan or infinity) are not permitted."
|
| 256 |
+
)
|
| 257 |
+
with pytest.raises(ValidationError):
|
| 258 |
+
field.deserialize(m2)
|
| 259 |
+
with pytest.raises(ValidationError):
|
| 260 |
+
field.deserialize(m3)
|
| 261 |
+
with pytest.raises(ValidationError):
|
| 262 |
+
field.deserialize(m4)
|
| 263 |
+
with pytest.raises(ValidationError):
|
| 264 |
+
field.deserialize(m5)
|
| 265 |
+
with pytest.raises(ValidationError):
|
| 266 |
+
field.deserialize(m6)
|
| 267 |
+
|
| 268 |
+
m7d = field.deserialize(m7)
|
| 269 |
+
assert isinstance(m7d, decimal.Decimal)
|
| 270 |
+
assert m7d.is_zero() and m7d.is_signed()
|
| 271 |
+
|
| 272 |
+
@pytest.mark.parametrize("allow_nan", (None, False, True))
|
| 273 |
+
@pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf"))
|
| 274 |
+
def test_float_field_allow_nan(self, value, allow_nan):
|
| 275 |
+
if allow_nan is None:
|
| 276 |
+
# Test default case is False
|
| 277 |
+
field = fields.Float()
|
| 278 |
+
else:
|
| 279 |
+
field = fields.Float(allow_nan=allow_nan)
|
| 280 |
+
|
| 281 |
+
if allow_nan is True:
|
| 282 |
+
res = field.deserialize(value)
|
| 283 |
+
assert isinstance(res, float)
|
| 284 |
+
if value.endswith("nan"):
|
| 285 |
+
assert math.isnan(res)
|
| 286 |
+
else:
|
| 287 |
+
assert res == float(value)
|
| 288 |
+
else:
|
| 289 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 290 |
+
field.deserialize(value)
|
| 291 |
+
assert str(excinfo.value.args[0]) == (
|
| 292 |
+
"Special numeric values (nan or infinity) are not permitted."
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
def test_string_field_deserialization(self):
|
| 296 |
+
field = fields.String()
|
| 297 |
+
assert field.deserialize("foo") == "foo"
|
| 298 |
+
assert field.deserialize(b"foo") == "foo"
|
| 299 |
+
|
| 300 |
+
# https://github.com/marshmallow-code/marshmallow/issues/231
|
| 301 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 302 |
+
field.deserialize(42)
|
| 303 |
+
assert excinfo.value.args[0] == "Not a valid string."
|
| 304 |
+
|
| 305 |
+
with pytest.raises(ValidationError):
|
| 306 |
+
field.deserialize({})
|
| 307 |
+
|
| 308 |
+
def test_boolean_field_deserialization(self):
|
| 309 |
+
field = fields.Boolean()
|
| 310 |
+
assert field.deserialize(True) is True
|
| 311 |
+
assert field.deserialize(False) is False
|
| 312 |
+
assert field.deserialize("True") is True
|
| 313 |
+
assert field.deserialize("False") is False
|
| 314 |
+
assert field.deserialize("true") is True
|
| 315 |
+
assert field.deserialize("false") is False
|
| 316 |
+
assert field.deserialize("1") is True
|
| 317 |
+
assert field.deserialize("0") is False
|
| 318 |
+
assert field.deserialize("on") is True
|
| 319 |
+
assert field.deserialize("ON") is True
|
| 320 |
+
assert field.deserialize("On") is True
|
| 321 |
+
assert field.deserialize("off") is False
|
| 322 |
+
assert field.deserialize("OFF") is False
|
| 323 |
+
assert field.deserialize("Off") is False
|
| 324 |
+
assert field.deserialize("y") is True
|
| 325 |
+
assert field.deserialize("Y") is True
|
| 326 |
+
assert field.deserialize("yes") is True
|
| 327 |
+
assert field.deserialize("YES") is True
|
| 328 |
+
assert field.deserialize("Yes") is True
|
| 329 |
+
assert field.deserialize("n") is False
|
| 330 |
+
assert field.deserialize("N") is False
|
| 331 |
+
assert field.deserialize("no") is False
|
| 332 |
+
assert field.deserialize("NO") is False
|
| 333 |
+
assert field.deserialize("No") is False
|
| 334 |
+
assert field.deserialize(1) is True
|
| 335 |
+
assert field.deserialize(0) is False
|
| 336 |
+
|
| 337 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 338 |
+
field.deserialize({})
|
| 339 |
+
assert excinfo.value.args[0] == "Not a valid boolean."
|
| 340 |
+
|
| 341 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 342 |
+
field.deserialize(42)
|
| 343 |
+
|
| 344 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 345 |
+
field.deserialize("invalid-string")
|
| 346 |
+
|
| 347 |
+
def test_boolean_field_deserialization_with_custom_truthy_values(self):
|
| 348 |
+
class MyBoolean(fields.Boolean):
|
| 349 |
+
truthy = {"yep"}
|
| 350 |
+
|
| 351 |
+
field = MyBoolean()
|
| 352 |
+
assert field.deserialize("yep") is True
|
| 353 |
+
|
| 354 |
+
field = fields.Boolean(truthy=("yep",))
|
| 355 |
+
assert field.deserialize("yep") is True
|
| 356 |
+
assert field.deserialize(False) is False
|
| 357 |
+
|
| 358 |
+
@pytest.mark.parametrize("in_val", ["notvalid", 123])
|
| 359 |
+
def test_boolean_field_deserialization_with_custom_truthy_values_invalid(
|
| 360 |
+
self, in_val
|
| 361 |
+
):
|
| 362 |
+
class MyBoolean(fields.Boolean):
|
| 363 |
+
truthy = {"yep"}
|
| 364 |
+
|
| 365 |
+
field = MyBoolean()
|
| 366 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 367 |
+
field.deserialize(in_val)
|
| 368 |
+
expected_msg = "Not a valid boolean."
|
| 369 |
+
assert str(excinfo.value.args[0]) == expected_msg
|
| 370 |
+
|
| 371 |
+
field = fields.Boolean(truthy=("yep",))
|
| 372 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 373 |
+
field.deserialize(in_val)
|
| 374 |
+
expected_msg = "Not a valid boolean."
|
| 375 |
+
assert str(excinfo.value.args[0]) == expected_msg
|
| 376 |
+
|
| 377 |
+
field2 = MyBoolean(error_messages={"invalid": "bad input"})
|
| 378 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 379 |
+
field2.deserialize(in_val)
|
| 380 |
+
assert str(excinfo.value.args[0]) == "bad input"
|
| 381 |
+
|
| 382 |
+
field2 = fields.Boolean(
|
| 383 |
+
truthy=("yep",), error_messages={"invalid": "bad input"}
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
def test_boolean_field_deserialization_with_empty_truthy(self):
|
| 387 |
+
field = fields.Boolean(truthy=())
|
| 388 |
+
assert field.deserialize("yep") is True
|
| 389 |
+
assert field.deserialize(True) is True
|
| 390 |
+
assert field.deserialize(False) is False
|
| 391 |
+
|
| 392 |
+
def test_boolean_field_deserialization_with_custom_falsy_values(self):
|
| 393 |
+
field = fields.Boolean(falsy=("nope",))
|
| 394 |
+
assert field.deserialize("nope") is False
|
| 395 |
+
assert field.deserialize(True) is True
|
| 396 |
+
|
| 397 |
+
def test_field_toggle_show_invalid_value_in_error_message(self):
|
| 398 |
+
error_messages = {"invalid": "Not valid: {input}"}
|
| 399 |
+
boolfield = fields.Boolean(error_messages=error_messages)
|
| 400 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 401 |
+
boolfield.deserialize("notabool")
|
| 402 |
+
assert str(excinfo.value.args[0]) == "Not valid: notabool"
|
| 403 |
+
|
| 404 |
+
numfield = fields.Number(error_messages=error_messages)
|
| 405 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 406 |
+
numfield.deserialize("notanum")
|
| 407 |
+
assert str(excinfo.value.args[0]) == "Not valid: notanum"
|
| 408 |
+
|
| 409 |
+
intfield = fields.Integer(error_messages=error_messages)
|
| 410 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 411 |
+
intfield.deserialize("notanint")
|
| 412 |
+
assert str(excinfo.value.args[0]) == "Not valid: notanint"
|
| 413 |
+
|
| 414 |
+
date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"}
|
| 415 |
+
datefield = fields.DateTime(error_messages=date_error_messages)
|
| 416 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 417 |
+
datefield.deserialize("notadate")
|
| 418 |
+
assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate"
|
| 419 |
+
|
| 420 |
+
@pytest.mark.parametrize(
|
| 421 |
+
"in_value",
|
| 422 |
+
[
|
| 423 |
+
"not-a-datetime",
|
| 424 |
+
42,
|
| 425 |
+
True,
|
| 426 |
+
False,
|
| 427 |
+
0,
|
| 428 |
+
"",
|
| 429 |
+
[],
|
| 430 |
+
"2018",
|
| 431 |
+
"2018-01-01",
|
| 432 |
+
dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"),
|
| 433 |
+
dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"),
|
| 434 |
+
],
|
| 435 |
+
)
|
| 436 |
+
def test_invalid_datetime_deserialization(self, in_value):
|
| 437 |
+
field = fields.DateTime()
|
| 438 |
+
with pytest.raises(ValidationError, match="Not a valid datetime."):
|
| 439 |
+
field.deserialize(in_value)
|
| 440 |
+
|
| 441 |
+
def test_custom_date_format_datetime_field_deserialization(self):
|
| 442 |
+
# Datetime string with format "%H:%M:%S.%f %Y-%m-%d"
|
| 443 |
+
datestring = "10:11:12.123456 2019-01-02"
|
| 444 |
+
|
| 445 |
+
# Deserialization should fail when datestring is not of same format
|
| 446 |
+
field = fields.DateTime(format="%d-%m-%Y %H:%M:%S")
|
| 447 |
+
with pytest.raises(ValidationError, match="Not a valid datetime."):
|
| 448 |
+
field.deserialize(datestring)
|
| 449 |
+
|
| 450 |
+
field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d")
|
| 451 |
+
assert field.deserialize(datestring) == dt.datetime(
|
| 452 |
+
2019, 1, 2, 10, 11, 12, 123456
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d")
|
| 456 |
+
assert field.deserialize(datestring) == dt.datetime(
|
| 457 |
+
2019, 1, 2, 10, 11, 12, 123456
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d")
|
| 461 |
+
with pytest.raises(ValidationError, match="Not a valid aware datetime."):
|
| 462 |
+
field.deserialize(datestring)
|
| 463 |
+
|
| 464 |
+
@pytest.mark.parametrize("fmt", ["rfc", "rfc822"])
|
| 465 |
+
@pytest.mark.parametrize(
|
| 466 |
+
("value", "expected", "aware"),
|
| 467 |
+
[
|
| 468 |
+
(
|
| 469 |
+
"Sun, 10 Nov 2013 01:23:45 -0000",
|
| 470 |
+
dt.datetime(2013, 11, 10, 1, 23, 45),
|
| 471 |
+
False,
|
| 472 |
+
),
|
| 473 |
+
(
|
| 474 |
+
"Sun, 10 Nov 2013 01:23:45 +0000",
|
| 475 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
|
| 476 |
+
True,
|
| 477 |
+
),
|
| 478 |
+
(
|
| 479 |
+
"Sun, 10 Nov 2013 01:23:45 -0600",
|
| 480 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central),
|
| 481 |
+
True,
|
| 482 |
+
),
|
| 483 |
+
],
|
| 484 |
+
)
|
| 485 |
+
def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware):
|
| 486 |
+
field = fields.DateTime(format=fmt)
|
| 487 |
+
assert field.deserialize(value) == expected
|
| 488 |
+
field = fields.NaiveDateTime(format=fmt)
|
| 489 |
+
if aware:
|
| 490 |
+
with pytest.raises(ValidationError, match="Not a valid naive datetime."):
|
| 491 |
+
field.deserialize(value)
|
| 492 |
+
else:
|
| 493 |
+
assert field.deserialize(value) == expected
|
| 494 |
+
field = fields.AwareDateTime(format=fmt)
|
| 495 |
+
if not aware:
|
| 496 |
+
with pytest.raises(ValidationError, match="Not a valid aware datetime."):
|
| 497 |
+
field.deserialize(value)
|
| 498 |
+
else:
|
| 499 |
+
assert field.deserialize(value) == expected
|
| 500 |
+
|
| 501 |
+
@pytest.mark.parametrize("fmt", ["iso", "iso8601"])
|
| 502 |
+
@pytest.mark.parametrize(
|
| 503 |
+
("value", "expected", "aware"),
|
| 504 |
+
[
|
| 505 |
+
("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False),
|
| 506 |
+
(
|
| 507 |
+
"2013-11-10T01:23:45+00:00",
|
| 508 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
|
| 509 |
+
True,
|
| 510 |
+
),
|
| 511 |
+
(
|
| 512 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251
|
| 513 |
+
"2013-11-10T01:23:45.123+00:00",
|
| 514 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc),
|
| 515 |
+
True,
|
| 516 |
+
),
|
| 517 |
+
(
|
| 518 |
+
"2013-11-10T01:23:45.123456+00:00",
|
| 519 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc),
|
| 520 |
+
True,
|
| 521 |
+
),
|
| 522 |
+
(
|
| 523 |
+
"2013-11-10T01:23:45-06:00",
|
| 524 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central),
|
| 525 |
+
True,
|
| 526 |
+
),
|
| 527 |
+
],
|
| 528 |
+
)
|
| 529 |
+
def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware):
|
| 530 |
+
field = fields.DateTime(format=fmt)
|
| 531 |
+
assert field.deserialize(value) == expected
|
| 532 |
+
field = fields.NaiveDateTime(format=fmt)
|
| 533 |
+
if aware:
|
| 534 |
+
with pytest.raises(ValidationError, match="Not a valid naive datetime."):
|
| 535 |
+
field.deserialize(value)
|
| 536 |
+
else:
|
| 537 |
+
assert field.deserialize(value) == expected
|
| 538 |
+
field = fields.AwareDateTime(format=fmt)
|
| 539 |
+
if not aware:
|
| 540 |
+
with pytest.raises(ValidationError, match="Not a valid aware datetime."):
|
| 541 |
+
field.deserialize(value)
|
| 542 |
+
else:
|
| 543 |
+
assert field.deserialize(value) == expected
|
| 544 |
+
|
| 545 |
+
@pytest.mark.parametrize(
|
| 546 |
+
("fmt", "value", "expected"),
|
| 547 |
+
[
|
| 548 |
+
("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)),
|
| 549 |
+
("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)),
|
| 550 |
+
("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)),
|
| 551 |
+
("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)),
|
| 552 |
+
(
|
| 553 |
+
"timestamp",
|
| 554 |
+
1384043025.123456,
|
| 555 |
+
dt.datetime(2013, 11, 10, 0, 23, 45, 123456),
|
| 556 |
+
),
|
| 557 |
+
("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)),
|
| 558 |
+
("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)),
|
| 559 |
+
("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)),
|
| 560 |
+
],
|
| 561 |
+
)
|
| 562 |
+
def test_timestamp_field_deserialization(self, fmt, value, expected):
|
| 563 |
+
field = fields.DateTime(format=fmt)
|
| 564 |
+
assert field.deserialize(value) == expected
|
| 565 |
+
|
| 566 |
+
# By default, a datetime from a timestamp is never aware.
|
| 567 |
+
field = fields.NaiveDateTime(format=fmt)
|
| 568 |
+
assert field.deserialize(value) == expected
|
| 569 |
+
|
| 570 |
+
field = fields.AwareDateTime(format=fmt)
|
| 571 |
+
with pytest.raises(ValidationError, match="Not a valid aware datetime."):
|
| 572 |
+
field.deserialize(value)
|
| 573 |
+
|
| 574 |
+
# But it can be added by providing a default.
|
| 575 |
+
field = fields.AwareDateTime(format=fmt, default_timezone=central)
|
| 576 |
+
expected_aware = expected.replace(tzinfo=central)
|
| 577 |
+
assert field.deserialize(value) == expected_aware
|
| 578 |
+
|
| 579 |
+
@pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"])
|
| 580 |
+
@pytest.mark.parametrize(
|
| 581 |
+
"in_value",
|
| 582 |
+
["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)],
|
| 583 |
+
)
|
| 584 |
+
def test_invalid_timestamp_field_deserialization(self, fmt, in_value):
|
| 585 |
+
field = fields.DateTime(format=fmt)
|
| 586 |
+
with pytest.raises(ValidationError, match="Not a valid datetime."):
|
| 587 |
+
field.deserialize(in_value)
|
| 588 |
+
|
| 589 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102
|
| 590 |
+
@pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"])
|
| 591 |
+
@pytest.mark.parametrize(
|
| 592 |
+
"mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError]
|
| 593 |
+
)
|
| 594 |
+
def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp):
|
| 595 |
+
with patch("datetime.datetime", mock_fromtimestamp):
|
| 596 |
+
field = fields.DateTime(format=fmt)
|
| 597 |
+
with pytest.raises(ValidationError, match="Not a valid datetime."):
|
| 598 |
+
field.deserialize(99999999999999999)
|
| 599 |
+
|
| 600 |
+
@pytest.mark.parametrize(
|
| 601 |
+
("fmt", "timezone", "value", "expected"),
|
| 602 |
+
[
|
| 603 |
+
("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)),
|
| 604 |
+
(
|
| 605 |
+
"iso",
|
| 606 |
+
dt.timezone.utc,
|
| 607 |
+
"2013-11-10T01:23:45+00:00",
|
| 608 |
+
dt.datetime(2013, 11, 10, 1, 23, 45),
|
| 609 |
+
),
|
| 610 |
+
(
|
| 611 |
+
"iso",
|
| 612 |
+
central,
|
| 613 |
+
"2013-11-10T01:23:45-03:00",
|
| 614 |
+
dt.datetime(2013, 11, 9, 22, 23, 45),
|
| 615 |
+
),
|
| 616 |
+
(
|
| 617 |
+
"rfc",
|
| 618 |
+
None,
|
| 619 |
+
"Sun, 10 Nov 2013 01:23:45 -0000",
|
| 620 |
+
dt.datetime(2013, 11, 10, 1, 23, 45),
|
| 621 |
+
),
|
| 622 |
+
(
|
| 623 |
+
"rfc",
|
| 624 |
+
dt.timezone.utc,
|
| 625 |
+
"Sun, 10 Nov 2013 01:23:45 +0000",
|
| 626 |
+
dt.datetime(2013, 11, 10, 1, 23, 45),
|
| 627 |
+
),
|
| 628 |
+
(
|
| 629 |
+
"rfc",
|
| 630 |
+
central,
|
| 631 |
+
"Sun, 10 Nov 2013 01:23:45 -0300",
|
| 632 |
+
dt.datetime(2013, 11, 9, 22, 23, 45),
|
| 633 |
+
),
|
| 634 |
+
],
|
| 635 |
+
)
|
| 636 |
+
def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected):
|
| 637 |
+
field = fields.NaiveDateTime(format=fmt, timezone=timezone)
|
| 638 |
+
assert field.deserialize(value) == expected
|
| 639 |
+
|
| 640 |
+
@pytest.mark.parametrize("timezone", (dt.timezone.utc, central))
|
| 641 |
+
@pytest.mark.parametrize(
|
| 642 |
+
("fmt", "value"),
|
| 643 |
+
[("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")],
|
| 644 |
+
)
|
| 645 |
+
def test_aware_datetime_default_timezone(self, fmt, timezone, value):
|
| 646 |
+
field = fields.AwareDateTime(format=fmt, default_timezone=timezone)
|
| 647 |
+
assert field.deserialize(value) == dt.datetime(
|
| 648 |
+
2013, 11, 10, 1, 23, 45, tzinfo=timezone
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
def test_time_field_deserialization(self):
|
| 652 |
+
field = fields.Time()
|
| 653 |
+
t = dt.time(1, 23, 45)
|
| 654 |
+
t_formatted = t.isoformat()
|
| 655 |
+
result = field.deserialize(t_formatted)
|
| 656 |
+
assert isinstance(result, dt.time)
|
| 657 |
+
assert_time_equal(result, t)
|
| 658 |
+
# With microseconds
|
| 659 |
+
t2 = dt.time(1, 23, 45, 6789)
|
| 660 |
+
t2_formatted = t2.isoformat()
|
| 661 |
+
result2 = field.deserialize(t2_formatted)
|
| 662 |
+
assert_time_equal(result2, t2)
|
| 663 |
+
|
| 664 |
+
@pytest.mark.parametrize("in_data", ["badvalue", "", [], 42])
|
| 665 |
+
def test_invalid_time_field_deserialization(self, in_data):
|
| 666 |
+
field = fields.Time()
|
| 667 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 668 |
+
field.deserialize(in_data)
|
| 669 |
+
assert excinfo.value.args[0] == "Not a valid time."
|
| 670 |
+
|
| 671 |
+
def test_custom_time_format_time_field_deserialization(self):
|
| 672 |
+
# Time string with format "%f.%S:%M:%H"
|
| 673 |
+
timestring = "123456.12:11:10"
|
| 674 |
+
|
| 675 |
+
# Deserialization should fail when timestring is not of same format
|
| 676 |
+
field = fields.Time(format="%S:%M:%H")
|
| 677 |
+
with pytest.raises(ValidationError, match="Not a valid time."):
|
| 678 |
+
field.deserialize(timestring)
|
| 679 |
+
|
| 680 |
+
field = fields.Time(format="%f.%S:%M:%H")
|
| 681 |
+
assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456)
|
| 682 |
+
|
| 683 |
+
@pytest.mark.parametrize("fmt", ["iso", "iso8601", None])
|
| 684 |
+
@pytest.mark.parametrize(
|
| 685 |
+
("value", "expected"),
|
| 686 |
+
[
|
| 687 |
+
("01:23:45", dt.time(1, 23, 45)),
|
| 688 |
+
("01:23:45+01:00", dt.time(1, 23, 45)),
|
| 689 |
+
("01:23:45.123", dt.time(1, 23, 45, 123000)),
|
| 690 |
+
("01:23:45.123456", dt.time(1, 23, 45, 123456)),
|
| 691 |
+
],
|
| 692 |
+
)
|
| 693 |
+
def test_iso_time_field_deserialization(self, fmt, value, expected):
|
| 694 |
+
if fmt is None:
|
| 695 |
+
field = fields.Time()
|
| 696 |
+
else:
|
| 697 |
+
field = fields.Time(format=fmt)
|
| 698 |
+
assert field.deserialize(value) == expected
|
| 699 |
+
|
| 700 |
+
def test_invalid_timedelta_precision(self):
|
| 701 |
+
with pytest.raises(ValueError, match='The precision must be "days",'):
|
| 702 |
+
fields.TimeDelta("invalid")
|
| 703 |
+
|
| 704 |
+
def test_timedelta_field_deserialization(self):
|
| 705 |
+
field = fields.TimeDelta()
|
| 706 |
+
result = field.deserialize("42")
|
| 707 |
+
assert isinstance(result, dt.timedelta)
|
| 708 |
+
assert result.days == 0
|
| 709 |
+
assert result.seconds == 42
|
| 710 |
+
assert result.microseconds == 0
|
| 711 |
+
|
| 712 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS)
|
| 713 |
+
result = field.deserialize(100000)
|
| 714 |
+
assert result.days == 1
|
| 715 |
+
assert result.seconds == 13600
|
| 716 |
+
assert result.microseconds == 0
|
| 717 |
+
|
| 718 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS)
|
| 719 |
+
result = field.deserialize("-42")
|
| 720 |
+
assert isinstance(result, dt.timedelta)
|
| 721 |
+
assert result.days == -42
|
| 722 |
+
assert result.seconds == 0
|
| 723 |
+
assert result.microseconds == 0
|
| 724 |
+
|
| 725 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
|
| 726 |
+
result = field.deserialize(10**6 + 1)
|
| 727 |
+
assert isinstance(result, dt.timedelta)
|
| 728 |
+
assert result.days == 0
|
| 729 |
+
assert result.seconds == 1
|
| 730 |
+
assert result.microseconds == 1
|
| 731 |
+
|
| 732 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
|
| 733 |
+
result = field.deserialize(86400 * 10**6 + 1)
|
| 734 |
+
assert isinstance(result, dt.timedelta)
|
| 735 |
+
assert result.days == 1
|
| 736 |
+
assert result.seconds == 0
|
| 737 |
+
assert result.microseconds == 1
|
| 738 |
+
|
| 739 |
+
field = fields.TimeDelta()
|
| 740 |
+
result = field.deserialize(12.9)
|
| 741 |
+
assert isinstance(result, dt.timedelta)
|
| 742 |
+
assert result.days == 0
|
| 743 |
+
assert result.seconds == 12
|
| 744 |
+
assert result.microseconds == 0
|
| 745 |
+
|
| 746 |
+
field = fields.TimeDelta(fields.TimeDelta.WEEKS)
|
| 747 |
+
result = field.deserialize(1)
|
| 748 |
+
assert isinstance(result, dt.timedelta)
|
| 749 |
+
assert result.days == 7
|
| 750 |
+
assert result.seconds == 0
|
| 751 |
+
assert result.microseconds == 0
|
| 752 |
+
|
| 753 |
+
field = fields.TimeDelta(fields.TimeDelta.HOURS)
|
| 754 |
+
result = field.deserialize(25)
|
| 755 |
+
assert isinstance(result, dt.timedelta)
|
| 756 |
+
assert result.days == 1
|
| 757 |
+
assert result.seconds == 3600
|
| 758 |
+
assert result.microseconds == 0
|
| 759 |
+
|
| 760 |
+
field = fields.TimeDelta(fields.TimeDelta.MINUTES)
|
| 761 |
+
result = field.deserialize(1441)
|
| 762 |
+
assert isinstance(result, dt.timedelta)
|
| 763 |
+
assert result.days == 1
|
| 764 |
+
assert result.seconds == 60
|
| 765 |
+
assert result.microseconds == 0
|
| 766 |
+
|
| 767 |
+
field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS)
|
| 768 |
+
result = field.deserialize(123456)
|
| 769 |
+
assert isinstance(result, dt.timedelta)
|
| 770 |
+
assert result.days == 0
|
| 771 |
+
assert result.seconds == 123
|
| 772 |
+
assert result.microseconds == 456000
|
| 773 |
+
|
| 774 |
+
total_microseconds_value = 322.0
|
| 775 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float)
|
| 776 |
+
result = field.deserialize(total_microseconds_value)
|
| 777 |
+
assert isinstance(result, dt.timedelta)
|
| 778 |
+
unit_value = dt.timedelta(microseconds=1).total_seconds()
|
| 779 |
+
assert math.isclose(
|
| 780 |
+
result.total_seconds() / unit_value, total_microseconds_value
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
total_microseconds_value = 322.12345
|
| 784 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float)
|
| 785 |
+
result = field.deserialize(total_microseconds_value)
|
| 786 |
+
assert isinstance(result, dt.timedelta)
|
| 787 |
+
unit_value = dt.timedelta(microseconds=1).total_seconds()
|
| 788 |
+
assert math.isclose(
|
| 789 |
+
result.total_seconds() / unit_value, math.floor(total_microseconds_value)
|
| 790 |
+
)
|
| 791 |
+
|
| 792 |
+
total_milliseconds_value = 322.223
|
| 793 |
+
field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float)
|
| 794 |
+
result = field.deserialize(total_milliseconds_value)
|
| 795 |
+
assert isinstance(result, dt.timedelta)
|
| 796 |
+
unit_value = dt.timedelta(milliseconds=1).total_seconds()
|
| 797 |
+
assert math.isclose(
|
| 798 |
+
result.total_seconds() / unit_value, total_milliseconds_value
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
total_seconds_value = 322.223
|
| 802 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS, float)
|
| 803 |
+
result = field.deserialize(total_seconds_value)
|
| 804 |
+
assert isinstance(result, dt.timedelta)
|
| 805 |
+
assert math.isclose(result.total_seconds(), total_seconds_value)
|
| 806 |
+
|
| 807 |
+
total_minutes_value = 322.223
|
| 808 |
+
field = fields.TimeDelta(fields.TimeDelta.MINUTES, float)
|
| 809 |
+
result = field.deserialize(total_minutes_value)
|
| 810 |
+
assert isinstance(result, dt.timedelta)
|
| 811 |
+
unit_value = dt.timedelta(minutes=1).total_seconds()
|
| 812 |
+
assert math.isclose(result.total_seconds() / unit_value, total_minutes_value)
|
| 813 |
+
|
| 814 |
+
total_hours_value = 322.223
|
| 815 |
+
field = fields.TimeDelta(fields.TimeDelta.HOURS, float)
|
| 816 |
+
result = field.deserialize(total_hours_value)
|
| 817 |
+
assert isinstance(result, dt.timedelta)
|
| 818 |
+
unit_value = dt.timedelta(hours=1).total_seconds()
|
| 819 |
+
assert math.isclose(result.total_seconds() / unit_value, total_hours_value)
|
| 820 |
+
|
| 821 |
+
total_days_value = 322.223
|
| 822 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS, float)
|
| 823 |
+
result = field.deserialize(total_days_value)
|
| 824 |
+
assert isinstance(result, dt.timedelta)
|
| 825 |
+
unit_value = dt.timedelta(days=1).total_seconds()
|
| 826 |
+
assert math.isclose(result.total_seconds() / unit_value, total_days_value)
|
| 827 |
+
|
| 828 |
+
total_weeks_value = 322.223
|
| 829 |
+
field = fields.TimeDelta(fields.TimeDelta.WEEKS, float)
|
| 830 |
+
result = field.deserialize(total_weeks_value)
|
| 831 |
+
assert isinstance(result, dt.timedelta)
|
| 832 |
+
unit_value = dt.timedelta(weeks=1).total_seconds()
|
| 833 |
+
assert math.isclose(result.total_seconds() / unit_value, total_weeks_value)
|
| 834 |
+
|
| 835 |
+
@pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999])
|
| 836 |
+
def test_invalid_timedelta_field_deserialization(self, in_value):
|
| 837 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS)
|
| 838 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 839 |
+
field.deserialize(in_value)
|
| 840 |
+
assert excinfo.value.args[0] == "Not a valid period of time."
|
| 841 |
+
|
| 842 |
+
@pytest.mark.parametrize("format", (None, "%Y-%m-%d"))
|
| 843 |
+
def test_date_field_deserialization(self, format):
|
| 844 |
+
field = fields.Date(format=format)
|
| 845 |
+
d = dt.date(2014, 8, 21)
|
| 846 |
+
iso_date = d.isoformat()
|
| 847 |
+
result = field.deserialize(iso_date)
|
| 848 |
+
assert type(result) is dt.date
|
| 849 |
+
assert_date_equal(result, d)
|
| 850 |
+
|
| 851 |
+
@pytest.mark.parametrize(
|
| 852 |
+
"in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")]
|
| 853 |
+
)
|
| 854 |
+
def test_invalid_date_field_deserialization(self, in_value):
|
| 855 |
+
field = fields.Date()
|
| 856 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 857 |
+
field.deserialize(in_value)
|
| 858 |
+
msg = "Not a valid date."
|
| 859 |
+
assert excinfo.value.args[0] == msg
|
| 860 |
+
|
| 861 |
+
def test_dict_field_deserialization(self):
|
| 862 |
+
data = {"foo": "bar"}
|
| 863 |
+
field = fields.Dict()
|
| 864 |
+
load = field.deserialize(data)
|
| 865 |
+
assert load == {"foo": "bar"}
|
| 866 |
+
# Check load is a distinct object
|
| 867 |
+
load["foo"] = "baz"
|
| 868 |
+
assert data["foo"] == "bar"
|
| 869 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 870 |
+
field.deserialize("baddict")
|
| 871 |
+
assert excinfo.value.args[0] == "Not a valid mapping type."
|
| 872 |
+
|
| 873 |
+
def test_structured_dict_value_deserialization(self):
|
| 874 |
+
field = fields.Dict(values=fields.List(fields.Str))
|
| 875 |
+
assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]}
|
| 876 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 877 |
+
field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]})
|
| 878 |
+
assert excinfo.value.args[0] == {
|
| 879 |
+
"foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}},
|
| 880 |
+
"bar": {"value": ["Not a valid list."]},
|
| 881 |
+
}
|
| 882 |
+
assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]}
|
| 883 |
+
|
| 884 |
+
def test_structured_dict_key_deserialization(self):
|
| 885 |
+
field = fields.Dict(keys=fields.Str)
|
| 886 |
+
assert field.deserialize({"foo": "bar"}) == {"foo": "bar"}
|
| 887 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 888 |
+
field.deserialize({1: "bar", "foo": "baz"})
|
| 889 |
+
assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}}
|
| 890 |
+
assert excinfo.value.valid_data == {"foo": "baz"}
|
| 891 |
+
|
| 892 |
+
def test_structured_dict_key_value_deserialization(self):
|
| 893 |
+
field = fields.Dict(
|
| 894 |
+
keys=fields.Str(
|
| 895 |
+
validate=[validate.Email(), validate.Regexp(r".*@test\.com$")]
|
| 896 |
+
),
|
| 897 |
+
values=fields.Decimal,
|
| 898 |
+
)
|
| 899 |
+
assert field.deserialize({"foo@test.com": 1}) == {
|
| 900 |
+
"foo@test.com": decimal.Decimal(1)
|
| 901 |
+
}
|
| 902 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 903 |
+
field.deserialize({1: "bar"})
|
| 904 |
+
assert excinfo.value.args[0] == {
|
| 905 |
+
1: {"key": ["Not a valid string."], "value": ["Not a valid number."]}
|
| 906 |
+
}
|
| 907 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 908 |
+
field.deserialize({"foo@test.com": "bar"})
|
| 909 |
+
assert excinfo.value.args[0] == {
|
| 910 |
+
"foo@test.com": {"value": ["Not a valid number."]}
|
| 911 |
+
}
|
| 912 |
+
assert excinfo.value.valid_data == {}
|
| 913 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 914 |
+
field.deserialize({1: 1})
|
| 915 |
+
assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}}
|
| 916 |
+
assert excinfo.value.valid_data == {}
|
| 917 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 918 |
+
field.deserialize({"foo": "bar"})
|
| 919 |
+
assert excinfo.value.args[0] == {
|
| 920 |
+
"foo": {
|
| 921 |
+
"key": [
|
| 922 |
+
"Not a valid email address.",
|
| 923 |
+
"String does not match expected pattern.",
|
| 924 |
+
],
|
| 925 |
+
"value": ["Not a valid number."],
|
| 926 |
+
}
|
| 927 |
+
}
|
| 928 |
+
assert excinfo.value.valid_data == {}
|
| 929 |
+
|
| 930 |
+
def test_url_field_deserialization(self):
|
| 931 |
+
field = fields.Url()
|
| 932 |
+
assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com"
|
| 933 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 934 |
+
field.deserialize("badurl")
|
| 935 |
+
assert excinfo.value.args[0][0] == "Not a valid URL."
|
| 936 |
+
# Relative URLS not allowed by default
|
| 937 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 938 |
+
field.deserialize("/foo/bar")
|
| 939 |
+
assert excinfo.value.args[0][0] == "Not a valid URL."
|
| 940 |
+
|
| 941 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/1400
|
| 942 |
+
def test_url_field_non_list_validators(self):
|
| 943 |
+
field = fields.Url(validate=(validate.Length(min=16),))
|
| 944 |
+
with pytest.raises(ValidationError, match="Shorter than minimum length"):
|
| 945 |
+
field.deserialize("https://abc.def")
|
| 946 |
+
|
| 947 |
+
def test_relative_url_field_deserialization(self):
|
| 948 |
+
field = fields.Url(relative=True)
|
| 949 |
+
assert field.deserialize("/foo/bar") == "/foo/bar"
|
| 950 |
+
|
| 951 |
+
def test_url_field_schemes_argument(self):
|
| 952 |
+
field = fields.URL()
|
| 953 |
+
url = "ws://test.test"
|
| 954 |
+
with pytest.raises(ValidationError):
|
| 955 |
+
field.deserialize(url)
|
| 956 |
+
field2 = fields.URL(schemes={"http", "https", "ws"})
|
| 957 |
+
assert field2.deserialize(url) == url
|
| 958 |
+
|
| 959 |
+
def test_email_field_deserialization(self):
|
| 960 |
+
field = fields.Email()
|
| 961 |
+
assert field.deserialize("foo@bar.com") == "foo@bar.com"
|
| 962 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 963 |
+
field.deserialize("invalidemail")
|
| 964 |
+
assert excinfo.value.args[0][0] == "Not a valid email address."
|
| 965 |
+
|
| 966 |
+
field = fields.Email(validate=[validate.Length(min=12)])
|
| 967 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 968 |
+
field.deserialize("foo@bar.com")
|
| 969 |
+
assert excinfo.value.args[0][0] == "Shorter than minimum length 12."
|
| 970 |
+
|
| 971 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/1400
|
| 972 |
+
def test_email_field_non_list_validators(self):
|
| 973 |
+
field = fields.Email(validate=(validate.Length(min=9),))
|
| 974 |
+
with pytest.raises(ValidationError, match="Shorter than minimum length"):
|
| 975 |
+
field.deserialize("a@bc.com")
|
| 976 |
+
|
| 977 |
+
def test_function_field_deserialization_is_noop_by_default(self):
|
| 978 |
+
field = fields.Function(lambda x: None)
|
| 979 |
+
# Default is noop
|
| 980 |
+
assert field.deserialize("foo") == "foo"
|
| 981 |
+
assert field.deserialize(42) == 42
|
| 982 |
+
|
| 983 |
+
def test_function_field_deserialization_with_callable(self):
|
| 984 |
+
field = fields.Function(lambda x: None, deserialize=lambda val: val.upper())
|
| 985 |
+
assert field.deserialize("foo") == "FOO"
|
| 986 |
+
|
| 987 |
+
def test_function_field_deserialization_with_context(self):
|
| 988 |
+
class Parent(Schema):
|
| 989 |
+
pass
|
| 990 |
+
|
| 991 |
+
field = fields.Function(
|
| 992 |
+
lambda x: None,
|
| 993 |
+
deserialize=lambda val, context: val.upper() + context["key"],
|
| 994 |
+
)
|
| 995 |
+
field.parent = Parent(context={"key": "BAR"})
|
| 996 |
+
assert field.deserialize("foo") == "FOOBAR"
|
| 997 |
+
|
| 998 |
+
def test_function_field_passed_deserialize_only_is_load_only(self):
|
| 999 |
+
field = fields.Function(deserialize=lambda val: val.upper())
|
| 1000 |
+
assert field.load_only is True
|
| 1001 |
+
|
| 1002 |
+
def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self):
|
| 1003 |
+
field = fields.Function(
|
| 1004 |
+
serialize=lambda val: val.lower(), deserialize=lambda val: val.upper()
|
| 1005 |
+
)
|
| 1006 |
+
assert field.load_only is False
|
| 1007 |
+
|
| 1008 |
+
def test_uuid_field_deserialization(self):
|
| 1009 |
+
field = fields.UUID()
|
| 1010 |
+
uuid_str = str(uuid.uuid4())
|
| 1011 |
+
result = field.deserialize(uuid_str)
|
| 1012 |
+
assert isinstance(result, uuid.UUID)
|
| 1013 |
+
assert str(result) == uuid_str
|
| 1014 |
+
|
| 1015 |
+
uuid4 = uuid.uuid4()
|
| 1016 |
+
result = field.deserialize(uuid4)
|
| 1017 |
+
assert isinstance(result, uuid.UUID)
|
| 1018 |
+
assert result == uuid4
|
| 1019 |
+
|
| 1020 |
+
uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf"
|
| 1021 |
+
result = field.deserialize(uuid_bytes)
|
| 1022 |
+
assert isinstance(result, uuid.UUID)
|
| 1023 |
+
assert result.bytes == uuid_bytes
|
| 1024 |
+
|
| 1025 |
+
@pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"])
|
| 1026 |
+
def test_invalid_uuid_deserialization(self, in_value):
|
| 1027 |
+
field = fields.UUID()
|
| 1028 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1029 |
+
field.deserialize(in_value)
|
| 1030 |
+
|
| 1031 |
+
assert excinfo.value.args[0] == "Not a valid UUID."
|
| 1032 |
+
|
| 1033 |
+
def test_ip_field_deserialization(self):
|
| 1034 |
+
field = fields.IP()
|
| 1035 |
+
ipv4_str = "140.82.118.3"
|
| 1036 |
+
result = field.deserialize(ipv4_str)
|
| 1037 |
+
assert isinstance(result, ipaddress.IPv4Address)
|
| 1038 |
+
assert str(result) == ipv4_str
|
| 1039 |
+
|
| 1040 |
+
ipv6_str = "2a00:1450:4001:824::200e"
|
| 1041 |
+
result = field.deserialize(ipv6_str)
|
| 1042 |
+
assert isinstance(result, ipaddress.IPv6Address)
|
| 1043 |
+
assert str(result) == ipv6_str
|
| 1044 |
+
|
| 1045 |
+
@pytest.mark.parametrize(
|
| 1046 |
+
"in_value",
|
| 1047 |
+
["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"],
|
| 1048 |
+
)
|
| 1049 |
+
def test_invalid_ip_deserialization(self, in_value):
|
| 1050 |
+
field = fields.IP()
|
| 1051 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1052 |
+
field.deserialize(in_value)
|
| 1053 |
+
|
| 1054 |
+
assert excinfo.value.args[0] == "Not a valid IP address."
|
| 1055 |
+
|
| 1056 |
+
def test_ipv4_field_deserialization(self):
|
| 1057 |
+
field = fields.IPv4()
|
| 1058 |
+
ipv4_str = "140.82.118.3"
|
| 1059 |
+
result = field.deserialize(ipv4_str)
|
| 1060 |
+
assert isinstance(result, ipaddress.IPv4Address)
|
| 1061 |
+
assert str(result) == ipv4_str
|
| 1062 |
+
|
| 1063 |
+
@pytest.mark.parametrize(
|
| 1064 |
+
"in_value",
|
| 1065 |
+
[
|
| 1066 |
+
"malformed",
|
| 1067 |
+
123,
|
| 1068 |
+
b"\x01\x02\03",
|
| 1069 |
+
"192.168",
|
| 1070 |
+
"192.168.0.1/24",
|
| 1071 |
+
"2a00:1450:4001:81d::200e",
|
| 1072 |
+
],
|
| 1073 |
+
)
|
| 1074 |
+
def test_invalid_ipv4_deserialization(self, in_value):
|
| 1075 |
+
field = fields.IPv4()
|
| 1076 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1077 |
+
field.deserialize(in_value)
|
| 1078 |
+
|
| 1079 |
+
assert excinfo.value.args[0] == "Not a valid IPv4 address."
|
| 1080 |
+
|
| 1081 |
+
def test_ipv6_field_deserialization(self):
|
| 1082 |
+
field = fields.IPv6()
|
| 1083 |
+
ipv6_str = "2a00:1450:4001:824::200e"
|
| 1084 |
+
result = field.deserialize(ipv6_str)
|
| 1085 |
+
assert isinstance(result, ipaddress.IPv6Address)
|
| 1086 |
+
assert str(result) == ipv6_str
|
| 1087 |
+
|
| 1088 |
+
def test_ipinterface_field_deserialization(self):
|
| 1089 |
+
field = fields.IPInterface()
|
| 1090 |
+
ipv4interface_str = "140.82.118.3/24"
|
| 1091 |
+
result = field.deserialize(ipv4interface_str)
|
| 1092 |
+
assert isinstance(result, ipaddress.IPv4Interface)
|
| 1093 |
+
assert str(result) == ipv4interface_str
|
| 1094 |
+
|
| 1095 |
+
ipv6interface_str = "2a00:1450:4001:824::200e/128"
|
| 1096 |
+
result = field.deserialize(ipv6interface_str)
|
| 1097 |
+
assert isinstance(result, ipaddress.IPv6Interface)
|
| 1098 |
+
assert str(result) == ipv6interface_str
|
| 1099 |
+
|
| 1100 |
+
@pytest.mark.parametrize(
|
| 1101 |
+
"in_value",
|
| 1102 |
+
[
|
| 1103 |
+
"malformed",
|
| 1104 |
+
123,
|
| 1105 |
+
b"\x01\x02\03",
|
| 1106 |
+
"192.168",
|
| 1107 |
+
"192.168.0.1/33",
|
| 1108 |
+
"ff::aa:1::2",
|
| 1109 |
+
"2a00:1450:4001:824::200e/129",
|
| 1110 |
+
],
|
| 1111 |
+
)
|
| 1112 |
+
def test_invalid_ipinterface_deserialization(self, in_value):
|
| 1113 |
+
field = fields.IPInterface()
|
| 1114 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1115 |
+
field.deserialize(in_value)
|
| 1116 |
+
|
| 1117 |
+
assert excinfo.value.args[0] == "Not a valid IP interface."
|
| 1118 |
+
|
| 1119 |
+
def test_ipv4interface_field_deserialization(self):
|
| 1120 |
+
field = fields.IPv4Interface()
|
| 1121 |
+
ipv4interface_str = "140.82.118.3/24"
|
| 1122 |
+
result = field.deserialize(ipv4interface_str)
|
| 1123 |
+
assert isinstance(result, ipaddress.IPv4Interface)
|
| 1124 |
+
assert str(result) == ipv4interface_str
|
| 1125 |
+
|
| 1126 |
+
@pytest.mark.parametrize(
|
| 1127 |
+
"in_value",
|
| 1128 |
+
[
|
| 1129 |
+
"malformed",
|
| 1130 |
+
123,
|
| 1131 |
+
b"\x01\x02\03",
|
| 1132 |
+
"192.168",
|
| 1133 |
+
"192.168.0.1/33",
|
| 1134 |
+
"2a00:1450:4001:81d::200e",
|
| 1135 |
+
"2a00:1450:4001:824::200e/129",
|
| 1136 |
+
],
|
| 1137 |
+
)
|
| 1138 |
+
def test_invalid_ipv4interface_deserialization(self, in_value):
|
| 1139 |
+
field = fields.IPv4Interface()
|
| 1140 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1141 |
+
field.deserialize(in_value)
|
| 1142 |
+
|
| 1143 |
+
assert excinfo.value.args[0] == "Not a valid IPv4 interface."
|
| 1144 |
+
|
| 1145 |
+
def test_ipv6interface_field_deserialization(self):
|
| 1146 |
+
field = fields.IPv6Interface()
|
| 1147 |
+
ipv6interface_str = "2a00:1450:4001:824::200e/128"
|
| 1148 |
+
result = field.deserialize(ipv6interface_str)
|
| 1149 |
+
assert isinstance(result, ipaddress.IPv6Interface)
|
| 1150 |
+
assert str(result) == ipv6interface_str
|
| 1151 |
+
|
| 1152 |
+
@pytest.mark.parametrize(
|
| 1153 |
+
"in_value",
|
| 1154 |
+
[
|
| 1155 |
+
"malformed",
|
| 1156 |
+
123,
|
| 1157 |
+
b"\x01\x02\03",
|
| 1158 |
+
"ff::aa:1::2",
|
| 1159 |
+
"192.168.0.1",
|
| 1160 |
+
"192.168.0.1/24",
|
| 1161 |
+
"2a00:1450:4001:824::200e/129",
|
| 1162 |
+
],
|
| 1163 |
+
)
|
| 1164 |
+
def test_invalid_ipv6interface_deserialization(self, in_value):
|
| 1165 |
+
field = fields.IPv6Interface()
|
| 1166 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1167 |
+
field.deserialize(in_value)
|
| 1168 |
+
|
| 1169 |
+
assert excinfo.value.args[0] == "Not a valid IPv6 interface."
|
| 1170 |
+
|
| 1171 |
+
def test_enum_field_by_symbol_deserialization(self):
|
| 1172 |
+
field = fields.Enum(GenderEnum)
|
| 1173 |
+
assert field.deserialize("male") == GenderEnum.male
|
| 1174 |
+
|
| 1175 |
+
def test_enum_field_by_symbol_invalid_value(self):
|
| 1176 |
+
field = fields.Enum(GenderEnum)
|
| 1177 |
+
with pytest.raises(
|
| 1178 |
+
ValidationError, match="Must be one of: male, female, non_binary."
|
| 1179 |
+
):
|
| 1180 |
+
field.deserialize("dummy")
|
| 1181 |
+
|
| 1182 |
+
def test_enum_field_by_symbol_not_string(self):
|
| 1183 |
+
field = fields.Enum(GenderEnum)
|
| 1184 |
+
with pytest.raises(ValidationError, match="Not a valid string."):
|
| 1185 |
+
field.deserialize(12)
|
| 1186 |
+
|
| 1187 |
+
def test_enum_field_by_value_true_deserialization(self):
|
| 1188 |
+
field = fields.Enum(HairColorEnum, by_value=True)
|
| 1189 |
+
assert field.deserialize("black hair") == HairColorEnum.black
|
| 1190 |
+
field = fields.Enum(GenderEnum, by_value=True)
|
| 1191 |
+
assert field.deserialize(1) == GenderEnum.male
|
| 1192 |
+
|
| 1193 |
+
def test_enum_field_by_value_field_deserialization(self):
|
| 1194 |
+
field = fields.Enum(HairColorEnum, by_value=fields.String)
|
| 1195 |
+
assert field.deserialize("black hair") == HairColorEnum.black
|
| 1196 |
+
field = fields.Enum(GenderEnum, by_value=fields.Integer)
|
| 1197 |
+
assert field.deserialize(1) == GenderEnum.male
|
| 1198 |
+
field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y"))
|
| 1199 |
+
assert field.deserialize("29/02/2004") == DateEnum.date_1
|
| 1200 |
+
|
| 1201 |
+
def test_enum_field_by_value_true_invalid_value(self):
|
| 1202 |
+
field = fields.Enum(HairColorEnum, by_value=True)
|
| 1203 |
+
with pytest.raises(
|
| 1204 |
+
ValidationError,
|
| 1205 |
+
match="Must be one of: black hair, brown hair, blond hair, red hair.",
|
| 1206 |
+
):
|
| 1207 |
+
field.deserialize("dummy")
|
| 1208 |
+
field = fields.Enum(GenderEnum, by_value=True)
|
| 1209 |
+
with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."):
|
| 1210 |
+
field.deserialize(12)
|
| 1211 |
+
|
| 1212 |
+
def test_enum_field_by_value_field_invalid_value(self):
|
| 1213 |
+
field = fields.Enum(HairColorEnum, by_value=fields.String)
|
| 1214 |
+
with pytest.raises(
|
| 1215 |
+
ValidationError,
|
| 1216 |
+
match="Must be one of: black hair, brown hair, blond hair, red hair.",
|
| 1217 |
+
):
|
| 1218 |
+
field.deserialize("dummy")
|
| 1219 |
+
field = fields.Enum(GenderEnum, by_value=fields.Integer)
|
| 1220 |
+
with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."):
|
| 1221 |
+
field.deserialize(12)
|
| 1222 |
+
field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y"))
|
| 1223 |
+
with pytest.raises(
|
| 1224 |
+
ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012."
|
| 1225 |
+
):
|
| 1226 |
+
field.deserialize("28/02/2004")
|
| 1227 |
+
|
| 1228 |
+
def test_enum_field_by_value_true_wrong_type(self):
|
| 1229 |
+
field = fields.Enum(HairColorEnum, by_value=True)
|
| 1230 |
+
with pytest.raises(
|
| 1231 |
+
ValidationError,
|
| 1232 |
+
match="Must be one of: black hair, brown hair, blond hair, red hair.",
|
| 1233 |
+
):
|
| 1234 |
+
field.deserialize("dummy")
|
| 1235 |
+
field = fields.Enum(GenderEnum, by_value=True)
|
| 1236 |
+
with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."):
|
| 1237 |
+
field.deserialize(12)
|
| 1238 |
+
|
| 1239 |
+
def test_enum_field_by_value_field_wrong_type(self):
|
| 1240 |
+
field = fields.Enum(HairColorEnum, by_value=fields.String)
|
| 1241 |
+
with pytest.raises(ValidationError, match="Not a valid string."):
|
| 1242 |
+
field.deserialize(12)
|
| 1243 |
+
field = fields.Enum(GenderEnum, by_value=fields.Integer)
|
| 1244 |
+
with pytest.raises(ValidationError, match="Not a valid integer."):
|
| 1245 |
+
field.deserialize("dummy")
|
| 1246 |
+
field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y"))
|
| 1247 |
+
with pytest.raises(ValidationError, match="Not a valid date."):
|
| 1248 |
+
field.deserialize("30/02/2004")
|
| 1249 |
+
|
| 1250 |
+
def test_deserialization_function_must_be_callable(self):
|
| 1251 |
+
with pytest.raises(TypeError):
|
| 1252 |
+
fields.Function(lambda x: None, deserialize="notvalid")
|
| 1253 |
+
|
| 1254 |
+
def test_method_field_deserialization_is_noop_by_default(self):
|
| 1255 |
+
class MiniUserSchema(Schema):
|
| 1256 |
+
uppername = fields.Method("uppercase_name")
|
| 1257 |
+
|
| 1258 |
+
def uppercase_name(self, obj):
|
| 1259 |
+
return obj.upper()
|
| 1260 |
+
|
| 1261 |
+
s = MiniUserSchema()
|
| 1262 |
+
assert s.fields["uppername"].deserialize("steve") == "steve"
|
| 1263 |
+
|
| 1264 |
+
def test_deserialization_method(self):
|
| 1265 |
+
class MiniUserSchema(Schema):
|
| 1266 |
+
uppername = fields.Method("uppercase_name", deserialize="lowercase_name")
|
| 1267 |
+
|
| 1268 |
+
def uppercase_name(self, obj):
|
| 1269 |
+
return obj.name.upper()
|
| 1270 |
+
|
| 1271 |
+
def lowercase_name(self, value):
|
| 1272 |
+
return value.lower()
|
| 1273 |
+
|
| 1274 |
+
s = MiniUserSchema()
|
| 1275 |
+
assert s.fields["uppername"].deserialize("STEVE") == "steve"
|
| 1276 |
+
|
| 1277 |
+
def test_deserialization_method_must_be_a_method(self):
|
| 1278 |
+
class BadSchema(Schema):
|
| 1279 |
+
uppername = fields.Method("uppercase_name", deserialize="lowercase_name")
|
| 1280 |
+
|
| 1281 |
+
with pytest.raises(AttributeError):
|
| 1282 |
+
BadSchema()
|
| 1283 |
+
|
| 1284 |
+
def test_method_field_deserialize_only(self):
|
| 1285 |
+
class MethodDeserializeOnly(Schema):
|
| 1286 |
+
name = fields.Method(deserialize="lowercase_name")
|
| 1287 |
+
|
| 1288 |
+
def lowercase_name(self, value):
|
| 1289 |
+
return value.lower()
|
| 1290 |
+
|
| 1291 |
+
assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec"
|
| 1292 |
+
|
| 1293 |
+
def test_datetime_list_field_deserialization(self):
|
| 1294 |
+
dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc)
|
| 1295 |
+
dstrings = [each.isoformat() for each in dtimes]
|
| 1296 |
+
field = fields.List(fields.DateTime())
|
| 1297 |
+
result = field.deserialize(dstrings)
|
| 1298 |
+
assert all(isinstance(each, dt.datetime) for each in result)
|
| 1299 |
+
for actual, expected in zip(result, dtimes):
|
| 1300 |
+
assert_date_equal(actual, expected)
|
| 1301 |
+
|
| 1302 |
+
def test_list_field_deserialize_invalid_item(self):
|
| 1303 |
+
field = fields.List(fields.DateTime)
|
| 1304 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1305 |
+
field.deserialize(["badvalue"])
|
| 1306 |
+
assert excinfo.value.args[0] == {0: ["Not a valid datetime."]}
|
| 1307 |
+
|
| 1308 |
+
field = fields.List(fields.Str())
|
| 1309 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1310 |
+
field.deserialize(["good", 42])
|
| 1311 |
+
assert excinfo.value.args[0] == {1: ["Not a valid string."]}
|
| 1312 |
+
|
| 1313 |
+
def test_list_field_deserialize_multiple_invalid_items(self):
|
| 1314 |
+
field = fields.List(
|
| 1315 |
+
fields.Int(
|
| 1316 |
+
validate=validate.Range(10, 20, error="Value {input} not in range")
|
| 1317 |
+
)
|
| 1318 |
+
)
|
| 1319 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1320 |
+
field.deserialize([10, 5, 25])
|
| 1321 |
+
assert len(excinfo.value.args[0]) == 2
|
| 1322 |
+
assert excinfo.value.args[0][1] == ["Value 5 not in range"]
|
| 1323 |
+
assert excinfo.value.args[0][2] == ["Value 25 not in range"]
|
| 1324 |
+
|
| 1325 |
+
@pytest.mark.parametrize("value", ["notalist", 42, {}])
|
| 1326 |
+
def test_list_field_deserialize_value_that_is_not_a_list(self, value):
|
| 1327 |
+
field = fields.List(fields.Str())
|
| 1328 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1329 |
+
field.deserialize(value)
|
| 1330 |
+
assert excinfo.value.args[0] == "Not a valid list."
|
| 1331 |
+
|
| 1332 |
+
def test_datetime_int_tuple_field_deserialization(self):
|
| 1333 |
+
dtime = dt.datetime.now()
|
| 1334 |
+
data = dtime.isoformat(), 42
|
| 1335 |
+
field = fields.Tuple([fields.DateTime(), fields.Integer()])
|
| 1336 |
+
result = field.deserialize(data)
|
| 1337 |
+
|
| 1338 |
+
assert isinstance(result, tuple)
|
| 1339 |
+
assert len(result) == 2
|
| 1340 |
+
for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)):
|
| 1341 |
+
assert isinstance(val, type_)
|
| 1342 |
+
assert val == true_val
|
| 1343 |
+
|
| 1344 |
+
def test_tuple_field_deserialize_invalid_item(self):
|
| 1345 |
+
field = fields.Tuple([fields.DateTime])
|
| 1346 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1347 |
+
field.deserialize(["badvalue"])
|
| 1348 |
+
assert excinfo.value.args[0] == {0: ["Not a valid datetime."]}
|
| 1349 |
+
|
| 1350 |
+
field = fields.Tuple([fields.Str(), fields.Integer()])
|
| 1351 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1352 |
+
field.deserialize(["good", "bad"])
|
| 1353 |
+
assert excinfo.value.args[0] == {1: ["Not a valid integer."]}
|
| 1354 |
+
|
| 1355 |
+
def test_tuple_field_deserialize_multiple_invalid_items(self):
|
| 1356 |
+
validator = validate.Range(10, 20, error="Value {input} not in range")
|
| 1357 |
+
field = fields.Tuple(
|
| 1358 |
+
[
|
| 1359 |
+
fields.Int(validate=validator),
|
| 1360 |
+
fields.Int(validate=validator),
|
| 1361 |
+
fields.Int(validate=validator),
|
| 1362 |
+
]
|
| 1363 |
+
)
|
| 1364 |
+
|
| 1365 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1366 |
+
field.deserialize([10, 5, 25])
|
| 1367 |
+
assert len(excinfo.value.args[0]) == 2
|
| 1368 |
+
assert excinfo.value.args[0][1] == ["Value 5 not in range"]
|
| 1369 |
+
assert excinfo.value.args[0][2] == ["Value 25 not in range"]
|
| 1370 |
+
|
| 1371 |
+
@pytest.mark.parametrize("value", ["notalist", 42, {}])
|
| 1372 |
+
def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value):
|
| 1373 |
+
field = fields.Tuple([fields.Str()])
|
| 1374 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1375 |
+
field.deserialize(value)
|
| 1376 |
+
assert excinfo.value.args[0] == "Not a valid tuple."
|
| 1377 |
+
|
| 1378 |
+
def test_tuple_field_deserialize_invalid_length(self):
|
| 1379 |
+
field = fields.Tuple([fields.Str(), fields.Str()])
|
| 1380 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1381 |
+
field.deserialize([42])
|
| 1382 |
+
assert excinfo.value.args[0] == "Length must be 2."
|
| 1383 |
+
|
| 1384 |
+
def test_constant_field_deserialization(self):
|
| 1385 |
+
field = fields.Constant("something")
|
| 1386 |
+
assert field.deserialize("whatever") == "something"
|
| 1387 |
+
|
| 1388 |
+
def test_constant_is_always_included_in_deserialized_data(self):
|
| 1389 |
+
class MySchema(Schema):
|
| 1390 |
+
foo = fields.Constant(42)
|
| 1391 |
+
|
| 1392 |
+
sch = MySchema()
|
| 1393 |
+
assert sch.load({})["foo"] == 42
|
| 1394 |
+
assert sch.load({"foo": 24})["foo"] == 42
|
| 1395 |
+
|
| 1396 |
+
def test_field_deserialization_with_user_validator_function(self):
|
| 1397 |
+
field = fields.String(validate=lambda s: s.lower() == "valid")
|
| 1398 |
+
assert field.deserialize("Valid") == "Valid"
|
| 1399 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1400 |
+
field.deserialize("invalid")
|
| 1401 |
+
assert excinfo.value.args[0][0] == "Invalid value."
|
| 1402 |
+
assert type(excinfo.value) is ValidationError
|
| 1403 |
+
|
| 1404 |
+
def test_field_deserialization_with_user_validator_class_that_returns_bool(self):
|
| 1405 |
+
class MyValidator:
|
| 1406 |
+
def __call__(self, val):
|
| 1407 |
+
if val == "valid":
|
| 1408 |
+
return True
|
| 1409 |
+
return False
|
| 1410 |
+
|
| 1411 |
+
field = fields.Field(validate=MyValidator())
|
| 1412 |
+
assert field.deserialize("valid") == "valid"
|
| 1413 |
+
with pytest.raises(ValidationError, match="Invalid value."):
|
| 1414 |
+
field.deserialize("invalid")
|
| 1415 |
+
|
| 1416 |
+
def test_field_deserialization_with_user_validator_that_raises_error_with_list(
|
| 1417 |
+
self,
|
| 1418 |
+
):
|
| 1419 |
+
def validator(val):
|
| 1420 |
+
raise ValidationError(["err1", "err2"])
|
| 1421 |
+
|
| 1422 |
+
class MySchema(Schema):
|
| 1423 |
+
foo = fields.Field(validate=validator)
|
| 1424 |
+
|
| 1425 |
+
errors = MySchema().validate({"foo": 42})
|
| 1426 |
+
assert errors["foo"] == ["err1", "err2"]
|
| 1427 |
+
|
| 1428 |
+
def test_validator_must_return_false_to_raise_error(self):
|
| 1429 |
+
# validator returns None, so anything validates
|
| 1430 |
+
field = fields.String(validate=lambda s: None)
|
| 1431 |
+
assert field.deserialize("Valid") == "Valid"
|
| 1432 |
+
# validator returns False, so nothing validates
|
| 1433 |
+
field2 = fields.String(validate=lambda s: False)
|
| 1434 |
+
with pytest.raises(ValidationError):
|
| 1435 |
+
field2.deserialize("invalid")
|
| 1436 |
+
|
| 1437 |
+
def test_field_deserialization_with_validator_with_nonascii_input(self):
|
| 1438 |
+
field = fields.String(validate=lambda s: False)
|
| 1439 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1440 |
+
field.deserialize("привет")
|
| 1441 |
+
assert type(excinfo.value) is ValidationError
|
| 1442 |
+
|
| 1443 |
+
def test_field_deserialization_with_user_validators(self):
|
| 1444 |
+
validators_gen = (
|
| 1445 |
+
func
|
| 1446 |
+
for func in (
|
| 1447 |
+
lambda s: s.lower() == "valid",
|
| 1448 |
+
lambda s: s.lower()[::-1] == "dilav",
|
| 1449 |
+
)
|
| 1450 |
+
)
|
| 1451 |
+
|
| 1452 |
+
m_colletion_type = [
|
| 1453 |
+
fields.String(
|
| 1454 |
+
validate=[
|
| 1455 |
+
lambda s: s.lower() == "valid",
|
| 1456 |
+
lambda s: s.lower()[::-1] == "dilav",
|
| 1457 |
+
]
|
| 1458 |
+
),
|
| 1459 |
+
fields.String(
|
| 1460 |
+
validate=(
|
| 1461 |
+
lambda s: s.lower() == "valid",
|
| 1462 |
+
lambda s: s.lower()[::-1] == "dilav",
|
| 1463 |
+
)
|
| 1464 |
+
),
|
| 1465 |
+
fields.String(validate=validators_gen),
|
| 1466 |
+
]
|
| 1467 |
+
|
| 1468 |
+
for field in m_colletion_type:
|
| 1469 |
+
assert field.deserialize("Valid") == "Valid"
|
| 1470 |
+
with pytest.raises(ValidationError, match="Invalid value."):
|
| 1471 |
+
field.deserialize("invalid")
|
| 1472 |
+
|
| 1473 |
+
def test_field_deserialization_with_custom_error_message(self):
|
| 1474 |
+
field = fields.String(
|
| 1475 |
+
validate=lambda s: s.lower() == "valid",
|
| 1476 |
+
error_messages={"validator_failed": "Bad value."},
|
| 1477 |
+
)
|
| 1478 |
+
with pytest.raises(ValidationError, match="Bad value."):
|
| 1479 |
+
field.deserialize("invalid")
|
| 1480 |
+
|
| 1481 |
+
|
| 1482 |
+
# No custom deserialization behavior, so a dict is returned
|
| 1483 |
+
class SimpleUserSchema(Schema):
|
| 1484 |
+
name = fields.String()
|
| 1485 |
+
age = fields.Float()
|
| 1486 |
+
|
| 1487 |
+
|
| 1488 |
+
class Validator(Schema):
|
| 1489 |
+
email = fields.Email()
|
| 1490 |
+
colors = fields.Str(validate=validate.OneOf(["red", "blue"]))
|
| 1491 |
+
age = fields.Integer(validate=lambda n: n > 0)
|
| 1492 |
+
|
| 1493 |
+
|
| 1494 |
+
class Validators(Schema):
|
| 1495 |
+
email = fields.Email()
|
| 1496 |
+
colors = fields.Str(validate=validate.OneOf(["red", "blue"]))
|
| 1497 |
+
age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100])
|
| 1498 |
+
|
| 1499 |
+
|
| 1500 |
+
class TestSchemaDeserialization:
|
| 1501 |
+
def test_deserialize_to_dict(self):
|
| 1502 |
+
user_dict = {"name": "Monty", "age": "42.3"}
|
| 1503 |
+
result = SimpleUserSchema().load(user_dict)
|
| 1504 |
+
assert result["name"] == "Monty"
|
| 1505 |
+
assert math.isclose(result["age"], 42.3)
|
| 1506 |
+
|
| 1507 |
+
def test_deserialize_with_missing_values(self):
|
| 1508 |
+
user_dict = {"name": "Monty"}
|
| 1509 |
+
result = SimpleUserSchema().load(user_dict)
|
| 1510 |
+
# 'age' is not included in result
|
| 1511 |
+
assert result == {"name": "Monty"}
|
| 1512 |
+
|
| 1513 |
+
def test_deserialize_many(self):
|
| 1514 |
+
users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}]
|
| 1515 |
+
result = SimpleUserSchema(many=True).load(users_data)
|
| 1516 |
+
assert isinstance(result, list)
|
| 1517 |
+
user = result[0]
|
| 1518 |
+
assert user["age"] == int(users_data[0]["age"])
|
| 1519 |
+
|
| 1520 |
+
def test_exclude(self):
|
| 1521 |
+
schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE)
|
| 1522 |
+
result = schema.load({"name": "Monty", "age": 42})
|
| 1523 |
+
assert "name" in result
|
| 1524 |
+
assert "age" not in result
|
| 1525 |
+
|
| 1526 |
+
def test_nested_single_deserialization_to_dict(self):
|
| 1527 |
+
class SimpleBlogSerializer(Schema):
|
| 1528 |
+
title = fields.String()
|
| 1529 |
+
author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE)
|
| 1530 |
+
|
| 1531 |
+
blog_dict = {
|
| 1532 |
+
"title": "Gimme Shelter",
|
| 1533 |
+
"author": {"name": "Mick", "age": "914", "email": "mick@stones.com"},
|
| 1534 |
+
}
|
| 1535 |
+
result = SimpleBlogSerializer().load(blog_dict)
|
| 1536 |
+
author = result["author"]
|
| 1537 |
+
assert author["name"] == "Mick"
|
| 1538 |
+
assert author["age"] == 914
|
| 1539 |
+
assert "email" not in author
|
| 1540 |
+
|
| 1541 |
+
def test_nested_list_deserialization_to_dict(self):
|
| 1542 |
+
class SimpleBlogSerializer(Schema):
|
| 1543 |
+
title = fields.String()
|
| 1544 |
+
authors = fields.Nested(SimpleUserSchema, many=True)
|
| 1545 |
+
|
| 1546 |
+
blog_dict = {
|
| 1547 |
+
"title": "Gimme Shelter",
|
| 1548 |
+
"authors": [
|
| 1549 |
+
{"name": "Mick", "age": "914"},
|
| 1550 |
+
{"name": "Keith", "age": "8442"},
|
| 1551 |
+
],
|
| 1552 |
+
}
|
| 1553 |
+
result = SimpleBlogSerializer().load(blog_dict)
|
| 1554 |
+
assert isinstance(result["authors"], list)
|
| 1555 |
+
author = result["authors"][0]
|
| 1556 |
+
assert author["name"] == "Mick"
|
| 1557 |
+
assert author["age"] == 914
|
| 1558 |
+
|
| 1559 |
+
def test_nested_single_none_not_allowed(self):
|
| 1560 |
+
class PetSchema(Schema):
|
| 1561 |
+
name = fields.Str()
|
| 1562 |
+
|
| 1563 |
+
class OwnerSchema(Schema):
|
| 1564 |
+
pet = fields.Nested(PetSchema(), allow_none=False)
|
| 1565 |
+
|
| 1566 |
+
sch = OwnerSchema()
|
| 1567 |
+
errors = sch.validate({"pet": None})
|
| 1568 |
+
assert "pet" in errors
|
| 1569 |
+
assert errors["pet"] == ["Field may not be null."]
|
| 1570 |
+
|
| 1571 |
+
def test_nested_many_non_not_allowed(self):
|
| 1572 |
+
class PetSchema(Schema):
|
| 1573 |
+
name = fields.Str()
|
| 1574 |
+
|
| 1575 |
+
class StoreSchema(Schema):
|
| 1576 |
+
pets = fields.Nested(PetSchema, allow_none=False, many=True)
|
| 1577 |
+
|
| 1578 |
+
sch = StoreSchema()
|
| 1579 |
+
errors = sch.validate({"pets": None})
|
| 1580 |
+
assert "pets" in errors
|
| 1581 |
+
assert errors["pets"] == ["Field may not be null."]
|
| 1582 |
+
|
| 1583 |
+
def test_nested_single_required_missing(self):
|
| 1584 |
+
class PetSchema(Schema):
|
| 1585 |
+
name = fields.Str()
|
| 1586 |
+
|
| 1587 |
+
class OwnerSchema(Schema):
|
| 1588 |
+
pet = fields.Nested(PetSchema(), required=True)
|
| 1589 |
+
|
| 1590 |
+
sch = OwnerSchema()
|
| 1591 |
+
errors = sch.validate({})
|
| 1592 |
+
assert "pet" in errors
|
| 1593 |
+
assert errors["pet"] == ["Missing data for required field."]
|
| 1594 |
+
|
| 1595 |
+
def test_nested_many_required_missing(self):
|
| 1596 |
+
class PetSchema(Schema):
|
| 1597 |
+
name = fields.Str()
|
| 1598 |
+
|
| 1599 |
+
class StoreSchema(Schema):
|
| 1600 |
+
pets = fields.Nested(PetSchema, required=True, many=True)
|
| 1601 |
+
|
| 1602 |
+
sch = StoreSchema()
|
| 1603 |
+
errors = sch.validate({})
|
| 1604 |
+
assert "pets" in errors
|
| 1605 |
+
assert errors["pets"] == ["Missing data for required field."]
|
| 1606 |
+
|
| 1607 |
+
def test_nested_only_basestring(self):
|
| 1608 |
+
class ANestedSchema(Schema):
|
| 1609 |
+
pk = fields.Str()
|
| 1610 |
+
|
| 1611 |
+
class MainSchema(Schema):
|
| 1612 |
+
pk = fields.Str()
|
| 1613 |
+
child = fields.Pluck(ANestedSchema, "pk")
|
| 1614 |
+
|
| 1615 |
+
sch = MainSchema()
|
| 1616 |
+
result = sch.load({"pk": "123", "child": "456"})
|
| 1617 |
+
assert result["child"]["pk"] == "456"
|
| 1618 |
+
|
| 1619 |
+
def test_nested_only_basestring_with_list_data(self):
|
| 1620 |
+
class ANestedSchema(Schema):
|
| 1621 |
+
pk = fields.Str()
|
| 1622 |
+
|
| 1623 |
+
class MainSchema(Schema):
|
| 1624 |
+
pk = fields.Str()
|
| 1625 |
+
children = fields.Pluck(ANestedSchema, "pk", many=True)
|
| 1626 |
+
|
| 1627 |
+
sch = MainSchema()
|
| 1628 |
+
result = sch.load({"pk": "123", "children": ["456", "789"]})
|
| 1629 |
+
assert result["children"][0]["pk"] == "456"
|
| 1630 |
+
assert result["children"][1]["pk"] == "789"
|
| 1631 |
+
|
| 1632 |
+
def test_nested_none_deserialization(self):
|
| 1633 |
+
class SimpleBlogSerializer(Schema):
|
| 1634 |
+
title = fields.String()
|
| 1635 |
+
author = fields.Nested(SimpleUserSchema, allow_none=True)
|
| 1636 |
+
|
| 1637 |
+
blog_dict = {"title": "Gimme Shelter", "author": None}
|
| 1638 |
+
result = SimpleBlogSerializer().load(blog_dict)
|
| 1639 |
+
assert result["author"] is None
|
| 1640 |
+
assert result["title"] == blog_dict["title"]
|
| 1641 |
+
|
| 1642 |
+
def test_deserialize_with_attribute_param(self):
|
| 1643 |
+
class AliasingUserSerializer(Schema):
|
| 1644 |
+
username = fields.Email(attribute="email")
|
| 1645 |
+
years = fields.Integer(attribute="age")
|
| 1646 |
+
|
| 1647 |
+
data = {"username": "foo@bar.com", "years": "42"}
|
| 1648 |
+
result = AliasingUserSerializer().load(data)
|
| 1649 |
+
assert result["email"] == "foo@bar.com"
|
| 1650 |
+
assert result["age"] == 42
|
| 1651 |
+
|
| 1652 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/450
|
| 1653 |
+
def test_deserialize_with_attribute_param_symmetry(self):
|
| 1654 |
+
class MySchema(Schema):
|
| 1655 |
+
foo = fields.Field(attribute="bar.baz")
|
| 1656 |
+
|
| 1657 |
+
schema = MySchema()
|
| 1658 |
+
dump_data = schema.dump({"bar": {"baz": 42}})
|
| 1659 |
+
assert dump_data == {"foo": 42}
|
| 1660 |
+
|
| 1661 |
+
load_data = schema.load({"foo": 42})
|
| 1662 |
+
assert load_data == {"bar": {"baz": 42}}
|
| 1663 |
+
|
| 1664 |
+
def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name(
|
| 1665 |
+
self,
|
| 1666 |
+
):
|
| 1667 |
+
class AliasingUserSerializer(Schema):
|
| 1668 |
+
username = fields.Email(attribute="email")
|
| 1669 |
+
years = fields.Integer(attribute="age")
|
| 1670 |
+
|
| 1671 |
+
data = {"username": "foobar.com", "years": "42"}
|
| 1672 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1673 |
+
AliasingUserSerializer().load(data)
|
| 1674 |
+
errors = excinfo.value.messages
|
| 1675 |
+
assert errors["username"] == ["Not a valid email address."]
|
| 1676 |
+
|
| 1677 |
+
def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name(
|
| 1678 |
+
self,
|
| 1679 |
+
):
|
| 1680 |
+
class AliasingUserSerializer(Schema):
|
| 1681 |
+
name = fields.String(data_key="Name")
|
| 1682 |
+
username = fields.Email(attribute="email", data_key="UserName")
|
| 1683 |
+
years = fields.Integer(attribute="age", data_key="Years")
|
| 1684 |
+
|
| 1685 |
+
data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"}
|
| 1686 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1687 |
+
AliasingUserSerializer().load(data)
|
| 1688 |
+
errors = excinfo.value.messages
|
| 1689 |
+
assert errors["UserName"] == ["Not a valid email address."]
|
| 1690 |
+
assert errors["Years"] == ["Not a valid integer."]
|
| 1691 |
+
|
| 1692 |
+
def test_deserialize_with_data_key_param(self):
|
| 1693 |
+
class AliasingUserSerializer(Schema):
|
| 1694 |
+
name = fields.String(data_key="Name")
|
| 1695 |
+
username = fields.Email(attribute="email", data_key="UserName")
|
| 1696 |
+
years = fields.Integer(data_key="Years")
|
| 1697 |
+
|
| 1698 |
+
data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"}
|
| 1699 |
+
result = AliasingUserSerializer(unknown=EXCLUDE).load(data)
|
| 1700 |
+
assert result["name"] == "Mick"
|
| 1701 |
+
assert result["email"] == "foo@bar.com"
|
| 1702 |
+
assert "years" not in result
|
| 1703 |
+
|
| 1704 |
+
def test_deserialize_with_data_key_as_empty_string(self):
|
| 1705 |
+
class MySchema(Schema):
|
| 1706 |
+
name = fields.Field(data_key="")
|
| 1707 |
+
|
| 1708 |
+
schema = MySchema()
|
| 1709 |
+
assert schema.load({"": "Grace"}) == {"name": "Grace"}
|
| 1710 |
+
|
| 1711 |
+
def test_deserialize_with_dump_only_param(self):
|
| 1712 |
+
class AliasingUserSerializer(Schema):
|
| 1713 |
+
name = fields.String()
|
| 1714 |
+
years = fields.Integer(dump_only=True)
|
| 1715 |
+
size = fields.Integer(dump_only=True, load_only=True)
|
| 1716 |
+
nicknames = fields.List(fields.Str(), dump_only=True)
|
| 1717 |
+
|
| 1718 |
+
data = {
|
| 1719 |
+
"name": "Mick",
|
| 1720 |
+
"years": "42",
|
| 1721 |
+
"size": "12",
|
| 1722 |
+
"nicknames": ["Your Majesty", "Brenda"],
|
| 1723 |
+
}
|
| 1724 |
+
result = AliasingUserSerializer(unknown=EXCLUDE).load(data)
|
| 1725 |
+
assert result["name"] == "Mick"
|
| 1726 |
+
assert "years" not in result
|
| 1727 |
+
assert "size" not in result
|
| 1728 |
+
assert "nicknames" not in result
|
| 1729 |
+
|
| 1730 |
+
def test_deserialize_with_missing_param_value(self):
|
| 1731 |
+
bdate = dt.datetime(2017, 9, 29)
|
| 1732 |
+
|
| 1733 |
+
class AliasingUserSerializer(Schema):
|
| 1734 |
+
name = fields.String()
|
| 1735 |
+
birthdate = fields.DateTime(load_default=bdate)
|
| 1736 |
+
|
| 1737 |
+
data = {"name": "Mick"}
|
| 1738 |
+
result = AliasingUserSerializer().load(data)
|
| 1739 |
+
assert result["name"] == "Mick"
|
| 1740 |
+
assert result["birthdate"] == bdate
|
| 1741 |
+
|
| 1742 |
+
def test_deserialize_with_missing_param_callable(self):
|
| 1743 |
+
bdate = dt.datetime(2017, 9, 29)
|
| 1744 |
+
|
| 1745 |
+
class AliasingUserSerializer(Schema):
|
| 1746 |
+
name = fields.String()
|
| 1747 |
+
birthdate = fields.DateTime(load_default=lambda: bdate)
|
| 1748 |
+
|
| 1749 |
+
data = {"name": "Mick"}
|
| 1750 |
+
result = AliasingUserSerializer().load(data)
|
| 1751 |
+
assert result["name"] == "Mick"
|
| 1752 |
+
assert result["birthdate"] == bdate
|
| 1753 |
+
|
| 1754 |
+
def test_deserialize_with_missing_param_none(self):
|
| 1755 |
+
class AliasingUserSerializer(Schema):
|
| 1756 |
+
name = fields.String()
|
| 1757 |
+
years = fields.Integer(load_default=None, allow_none=True)
|
| 1758 |
+
|
| 1759 |
+
data = {"name": "Mick"}
|
| 1760 |
+
result = AliasingUserSerializer().load(data)
|
| 1761 |
+
assert result["name"] == "Mick"
|
| 1762 |
+
assert result["years"] is None
|
| 1763 |
+
|
| 1764 |
+
def test_deserialization_raises_with_errors(self):
|
| 1765 |
+
bad_data = {"email": "invalid-email", "colors": "burger", "age": -1}
|
| 1766 |
+
v = Validator()
|
| 1767 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1768 |
+
v.load(bad_data)
|
| 1769 |
+
errors = excinfo.value.messages
|
| 1770 |
+
assert "email" in errors
|
| 1771 |
+
assert "colors" in errors
|
| 1772 |
+
assert "age" in errors
|
| 1773 |
+
|
| 1774 |
+
def test_deserialization_raises_with_errors_with_multiple_validators(self):
|
| 1775 |
+
bad_data = {"email": "invalid-email", "colors": "burger", "age": -1}
|
| 1776 |
+
v = Validators()
|
| 1777 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1778 |
+
v.load(bad_data)
|
| 1779 |
+
errors = excinfo.value.messages
|
| 1780 |
+
assert "email" in errors
|
| 1781 |
+
assert "colors" in errors
|
| 1782 |
+
assert "age" in errors
|
| 1783 |
+
|
| 1784 |
+
def test_deserialization_many_raises_errors(self):
|
| 1785 |
+
bad_data = [
|
| 1786 |
+
{"email": "foo@bar.com", "colors": "red", "age": 18},
|
| 1787 |
+
{"email": "bad", "colors": "pizza", "age": -1},
|
| 1788 |
+
]
|
| 1789 |
+
v = Validator(many=True)
|
| 1790 |
+
with pytest.raises(ValidationError):
|
| 1791 |
+
v.load(bad_data)
|
| 1792 |
+
|
| 1793 |
+
def test_validation_errors_are_stored(self):
|
| 1794 |
+
def validate_field(val):
|
| 1795 |
+
raise ValidationError("Something went wrong")
|
| 1796 |
+
|
| 1797 |
+
class MySchema(Schema):
|
| 1798 |
+
foo = fields.Field(validate=validate_field)
|
| 1799 |
+
|
| 1800 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1801 |
+
MySchema().load({"foo": 42})
|
| 1802 |
+
errors = excinfo.value.messages
|
| 1803 |
+
assert "Something went wrong" in errors["foo"]
|
| 1804 |
+
|
| 1805 |
+
def test_multiple_errors_can_be_stored_for_a_field(self):
|
| 1806 |
+
def validate_with_bool(n):
|
| 1807 |
+
return False
|
| 1808 |
+
|
| 1809 |
+
def validate_with_error(n):
|
| 1810 |
+
raise ValidationError("foo is not valid")
|
| 1811 |
+
|
| 1812 |
+
class MySchema(Schema):
|
| 1813 |
+
foo = fields.Field(
|
| 1814 |
+
required=True, validate=[validate_with_bool, validate_with_error]
|
| 1815 |
+
)
|
| 1816 |
+
|
| 1817 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1818 |
+
MySchema().load({"foo": "bar"})
|
| 1819 |
+
errors = excinfo.value.messages
|
| 1820 |
+
|
| 1821 |
+
assert type(errors["foo"]) is list
|
| 1822 |
+
assert len(errors["foo"]) == 2
|
| 1823 |
+
|
| 1824 |
+
def test_multiple_errors_can_be_stored_for_an_email_field(self):
|
| 1825 |
+
def validate_with_bool(val):
|
| 1826 |
+
return False
|
| 1827 |
+
|
| 1828 |
+
class MySchema(Schema):
|
| 1829 |
+
email = fields.Email(validate=[validate_with_bool])
|
| 1830 |
+
|
| 1831 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1832 |
+
MySchema().load({"email": "foo"})
|
| 1833 |
+
errors = excinfo.value.messages
|
| 1834 |
+
assert len(errors["email"]) == 2
|
| 1835 |
+
assert "Not a valid email address." in errors["email"][0]
|
| 1836 |
+
|
| 1837 |
+
def test_multiple_errors_can_be_stored_for_a_url_field(self):
|
| 1838 |
+
def validate_with_bool(val):
|
| 1839 |
+
return False
|
| 1840 |
+
|
| 1841 |
+
class MySchema(Schema):
|
| 1842 |
+
url = fields.Url(validate=[validate_with_bool])
|
| 1843 |
+
|
| 1844 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1845 |
+
MySchema().load({"url": "foo"})
|
| 1846 |
+
errors = excinfo.value.messages
|
| 1847 |
+
assert len(errors["url"]) == 2
|
| 1848 |
+
assert "Not a valid URL." in errors["url"][0]
|
| 1849 |
+
|
| 1850 |
+
def test_required_value_only_passed_to_validators_if_provided(self):
|
| 1851 |
+
class MySchema(Schema):
|
| 1852 |
+
foo = fields.Field(required=True, validate=lambda f: False)
|
| 1853 |
+
|
| 1854 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1855 |
+
MySchema().load({})
|
| 1856 |
+
errors = excinfo.value.messages
|
| 1857 |
+
# required value missing
|
| 1858 |
+
assert len(errors["foo"]) == 1
|
| 1859 |
+
assert "Missing data for required field." in errors["foo"]
|
| 1860 |
+
|
| 1861 |
+
@pytest.mark.parametrize("partial_schema", [True, False])
|
| 1862 |
+
def test_partial_deserialization(self, partial_schema):
|
| 1863 |
+
class MySchema(Schema):
|
| 1864 |
+
foo = fields.Field(required=True)
|
| 1865 |
+
bar = fields.Field(required=True)
|
| 1866 |
+
|
| 1867 |
+
schema_args = {}
|
| 1868 |
+
load_args = {}
|
| 1869 |
+
if partial_schema:
|
| 1870 |
+
schema_args["partial"] = True
|
| 1871 |
+
else:
|
| 1872 |
+
load_args["partial"] = True
|
| 1873 |
+
data = MySchema(**schema_args).load({"foo": 3}, **load_args)
|
| 1874 |
+
|
| 1875 |
+
assert data["foo"] == 3
|
| 1876 |
+
assert "bar" not in data
|
| 1877 |
+
|
| 1878 |
+
def test_partial_fields_deserialization(self):
|
| 1879 |
+
class MySchema(Schema):
|
| 1880 |
+
foo = fields.Field(required=True)
|
| 1881 |
+
bar = fields.Field(required=True)
|
| 1882 |
+
baz = fields.Field(required=True)
|
| 1883 |
+
|
| 1884 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1885 |
+
MySchema().load({"foo": 3}, partial=tuple())
|
| 1886 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 1887 |
+
assert data["foo"] == 3
|
| 1888 |
+
assert "bar" in errors
|
| 1889 |
+
assert "baz" in errors
|
| 1890 |
+
|
| 1891 |
+
data = MySchema().load({"foo": 3}, partial=("bar", "baz"))
|
| 1892 |
+
assert data["foo"] == 3
|
| 1893 |
+
assert "bar" not in data
|
| 1894 |
+
assert "baz" not in data
|
| 1895 |
+
|
| 1896 |
+
data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz"))
|
| 1897 |
+
assert data["foo"] == 3
|
| 1898 |
+
assert "bar" not in data
|
| 1899 |
+
assert "baz" not in data
|
| 1900 |
+
|
| 1901 |
+
def test_partial_fields_validation(self):
|
| 1902 |
+
class MySchema(Schema):
|
| 1903 |
+
foo = fields.Field(required=True)
|
| 1904 |
+
bar = fields.Field(required=True)
|
| 1905 |
+
baz = fields.Field(required=True)
|
| 1906 |
+
|
| 1907 |
+
errors = MySchema().validate({"foo": 3}, partial=tuple())
|
| 1908 |
+
assert "bar" in errors
|
| 1909 |
+
assert "baz" in errors
|
| 1910 |
+
|
| 1911 |
+
errors = MySchema().validate({"foo": 3}, partial=("bar", "baz"))
|
| 1912 |
+
assert errors == {}
|
| 1913 |
+
|
| 1914 |
+
errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz"))
|
| 1915 |
+
assert errors == {}
|
| 1916 |
+
|
| 1917 |
+
def test_unknown_fields_deserialization(self):
|
| 1918 |
+
class MySchema(Schema):
|
| 1919 |
+
foo = fields.Integer()
|
| 1920 |
+
|
| 1921 |
+
data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5})
|
| 1922 |
+
assert data["foo"] == 3
|
| 1923 |
+
assert "bar" not in data
|
| 1924 |
+
|
| 1925 |
+
data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE)
|
| 1926 |
+
assert data["foo"] == 3
|
| 1927 |
+
assert "bar" not in data
|
| 1928 |
+
|
| 1929 |
+
data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE)
|
| 1930 |
+
assert data["foo"] == 3
|
| 1931 |
+
assert data["bar"]
|
| 1932 |
+
|
| 1933 |
+
data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5})
|
| 1934 |
+
assert data["foo"] == 3
|
| 1935 |
+
assert data["bar"]
|
| 1936 |
+
|
| 1937 |
+
with pytest.raises(ValidationError, match="foo"):
|
| 1938 |
+
MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5})
|
| 1939 |
+
|
| 1940 |
+
data = MySchema(unknown=INCLUDE, many=True).load(
|
| 1941 |
+
[{"foo": 1}, {"foo": 3, "bar": 5}]
|
| 1942 |
+
)
|
| 1943 |
+
assert "foo" in data[1]
|
| 1944 |
+
assert "bar" in data[1]
|
| 1945 |
+
|
| 1946 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1947 |
+
MySchema().load({"foo": 3, "bar": 5})
|
| 1948 |
+
err = excinfo.value
|
| 1949 |
+
assert "bar" in err.messages
|
| 1950 |
+
assert err.messages["bar"] == ["Unknown field."]
|
| 1951 |
+
|
| 1952 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1953 |
+
MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}])
|
| 1954 |
+
err = excinfo.value
|
| 1955 |
+
assert 0 in err.messages
|
| 1956 |
+
assert "foo" in err.messages[0]
|
| 1957 |
+
assert err.messages[0]["foo"] == ["Not a valid integer."]
|
| 1958 |
+
assert 1 in err.messages
|
| 1959 |
+
assert "bar" in err.messages[1]
|
| 1960 |
+
assert err.messages[1]["bar"] == ["Unknown field."]
|
| 1961 |
+
|
| 1962 |
+
def test_unknown_fields_deserialization_precedence(self):
|
| 1963 |
+
class MySchema(Schema):
|
| 1964 |
+
class Meta:
|
| 1965 |
+
unknown = INCLUDE
|
| 1966 |
+
|
| 1967 |
+
foo = fields.Integer()
|
| 1968 |
+
|
| 1969 |
+
data = MySchema().load({"foo": 3, "bar": 5})
|
| 1970 |
+
assert data["foo"] == 3
|
| 1971 |
+
assert data["bar"] == 5
|
| 1972 |
+
|
| 1973 |
+
data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5})
|
| 1974 |
+
assert data["foo"] == 3
|
| 1975 |
+
assert "bar" not in data
|
| 1976 |
+
|
| 1977 |
+
data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE)
|
| 1978 |
+
assert data["foo"] == 3
|
| 1979 |
+
assert "bar" not in data
|
| 1980 |
+
|
| 1981 |
+
with pytest.raises(ValidationError):
|
| 1982 |
+
MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE)
|
| 1983 |
+
|
| 1984 |
+
def test_unknown_fields_deserialization_with_data_key(self):
|
| 1985 |
+
class MySchema(Schema):
|
| 1986 |
+
foo = fields.Integer(data_key="Foo")
|
| 1987 |
+
|
| 1988 |
+
data = MySchema().load({"Foo": 1})
|
| 1989 |
+
assert data["foo"] == 1
|
| 1990 |
+
assert "Foo" not in data
|
| 1991 |
+
|
| 1992 |
+
data = MySchema(unknown=RAISE).load({"Foo": 1})
|
| 1993 |
+
assert data["foo"] == 1
|
| 1994 |
+
assert "Foo" not in data
|
| 1995 |
+
|
| 1996 |
+
with pytest.raises(ValidationError):
|
| 1997 |
+
MySchema(unknown=RAISE).load({"foo": 1})
|
| 1998 |
+
|
| 1999 |
+
data = MySchema(unknown=INCLUDE).load({"Foo": 1})
|
| 2000 |
+
assert data["foo"] == 1
|
| 2001 |
+
assert "Foo" not in data
|
| 2002 |
+
|
| 2003 |
+
def test_unknown_fields_deserialization_with_index_errors_false(self):
|
| 2004 |
+
class MySchema(Schema):
|
| 2005 |
+
foo = fields.Integer()
|
| 2006 |
+
|
| 2007 |
+
class Meta:
|
| 2008 |
+
unknown = RAISE
|
| 2009 |
+
index_errors = False
|
| 2010 |
+
|
| 2011 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2012 |
+
MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}])
|
| 2013 |
+
err = excinfo.value
|
| 2014 |
+
assert 1 not in err.messages
|
| 2015 |
+
assert "foo" in err.messages
|
| 2016 |
+
assert "bar" in err.messages
|
| 2017 |
+
assert err.messages["foo"] == ["Not a valid integer."]
|
| 2018 |
+
assert err.messages["bar"] == ["Unknown field."]
|
| 2019 |
+
|
| 2020 |
+
def test_dump_only_fields_considered_unknown(self):
|
| 2021 |
+
class MySchema(Schema):
|
| 2022 |
+
foo = fields.Int(dump_only=True)
|
| 2023 |
+
|
| 2024 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2025 |
+
MySchema().load({"foo": 42})
|
| 2026 |
+
err = excinfo.value
|
| 2027 |
+
assert "foo" in err.messages
|
| 2028 |
+
assert err.messages["foo"] == ["Unknown field."]
|
| 2029 |
+
|
| 2030 |
+
# When unknown = INCLUDE, dump-only fields are included as unknown
|
| 2031 |
+
# without any validation.
|
| 2032 |
+
data = MySchema(unknown=INCLUDE).load({"foo": "LOL"})
|
| 2033 |
+
assert data["foo"] == "LOL"
|
| 2034 |
+
|
| 2035 |
+
def test_unknown_fields_do_not_unpack_dotted_names(self):
|
| 2036 |
+
class MySchema(Schema):
|
| 2037 |
+
class Meta:
|
| 2038 |
+
unknown = INCLUDE
|
| 2039 |
+
|
| 2040 |
+
foo = fields.Str()
|
| 2041 |
+
bar = fields.Str(data_key="bar.baz")
|
| 2042 |
+
|
| 2043 |
+
# dotted names are still supported
|
| 2044 |
+
data = MySchema().load({"foo": "hi", "bar.baz": "okay"})
|
| 2045 |
+
assert data == {"foo": "hi", "bar": "okay"}
|
| 2046 |
+
|
| 2047 |
+
# but extra keys included via unknown=INCLUDE are not transformed into nested dicts
|
| 2048 |
+
data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"})
|
| 2049 |
+
assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"}
|
| 2050 |
+
|
| 2051 |
+
|
| 2052 |
+
validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x])
|
| 2053 |
+
|
| 2054 |
+
validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0])
|
| 2055 |
+
|
| 2056 |
+
validators_gen_str = (
|
| 2057 |
+
func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"]
|
| 2058 |
+
)
|
| 2059 |
+
|
| 2060 |
+
|
| 2061 |
+
class TestValidation:
|
| 2062 |
+
def test_integer_with_validator(self):
|
| 2063 |
+
field = fields.Integer(validate=lambda x: 18 <= x <= 24)
|
| 2064 |
+
out = field.deserialize("20")
|
| 2065 |
+
assert out == 20
|
| 2066 |
+
with pytest.raises(ValidationError):
|
| 2067 |
+
field.deserialize(25)
|
| 2068 |
+
|
| 2069 |
+
@pytest.mark.parametrize(
|
| 2070 |
+
"field",
|
| 2071 |
+
[
|
| 2072 |
+
fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]),
|
| 2073 |
+
fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)),
|
| 2074 |
+
fields.Integer(validate=validators_gen),
|
| 2075 |
+
],
|
| 2076 |
+
)
|
| 2077 |
+
def test_integer_with_validators(self, field):
|
| 2078 |
+
out = field.deserialize("20")
|
| 2079 |
+
assert out == 20
|
| 2080 |
+
with pytest.raises(ValidationError):
|
| 2081 |
+
field.deserialize(25)
|
| 2082 |
+
|
| 2083 |
+
@pytest.mark.parametrize(
|
| 2084 |
+
"field",
|
| 2085 |
+
[
|
| 2086 |
+
fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]),
|
| 2087 |
+
fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)),
|
| 2088 |
+
fields.Float(validate=validators_gen_float),
|
| 2089 |
+
],
|
| 2090 |
+
)
|
| 2091 |
+
def test_float_with_validators(self, field):
|
| 2092 |
+
assert field.deserialize(3.14)
|
| 2093 |
+
with pytest.raises(ValidationError):
|
| 2094 |
+
field.deserialize(4.2)
|
| 2095 |
+
|
| 2096 |
+
def test_string_validator(self):
|
| 2097 |
+
field = fields.String(validate=lambda n: len(n) == 3)
|
| 2098 |
+
assert field.deserialize("Joe") == "Joe"
|
| 2099 |
+
with pytest.raises(ValidationError):
|
| 2100 |
+
field.deserialize("joseph")
|
| 2101 |
+
|
| 2102 |
+
def test_function_validator(self):
|
| 2103 |
+
field = fields.Function(
|
| 2104 |
+
lambda d: d.name.upper(), validate=lambda n: len(n) == 3
|
| 2105 |
+
)
|
| 2106 |
+
assert field.deserialize("joe")
|
| 2107 |
+
with pytest.raises(ValidationError):
|
| 2108 |
+
field.deserialize("joseph")
|
| 2109 |
+
|
| 2110 |
+
@pytest.mark.parametrize(
|
| 2111 |
+
"field",
|
| 2112 |
+
[
|
| 2113 |
+
fields.Function(
|
| 2114 |
+
lambda d: d.name.upper(),
|
| 2115 |
+
validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"],
|
| 2116 |
+
),
|
| 2117 |
+
fields.Function(
|
| 2118 |
+
lambda d: d.name.upper(),
|
| 2119 |
+
validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"),
|
| 2120 |
+
),
|
| 2121 |
+
fields.Function(lambda d: d.name.upper(), validate=validators_gen_str),
|
| 2122 |
+
],
|
| 2123 |
+
)
|
| 2124 |
+
def test_function_validators(self, field):
|
| 2125 |
+
assert field.deserialize("joe")
|
| 2126 |
+
with pytest.raises(ValidationError):
|
| 2127 |
+
field.deserialize("joseph")
|
| 2128 |
+
|
| 2129 |
+
def test_method_validator(self):
|
| 2130 |
+
class MethodSerializer(Schema):
|
| 2131 |
+
name = fields.Method(
|
| 2132 |
+
"get_name", deserialize="get_name", validate=lambda n: len(n) == 3
|
| 2133 |
+
)
|
| 2134 |
+
|
| 2135 |
+
def get_name(self, val):
|
| 2136 |
+
return val.upper()
|
| 2137 |
+
|
| 2138 |
+
assert MethodSerializer().load({"name": "joe"})
|
| 2139 |
+
with pytest.raises(ValidationError, match="Invalid value."):
|
| 2140 |
+
MethodSerializer().load({"name": "joseph"})
|
| 2141 |
+
|
| 2142 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/269
|
| 2143 |
+
def test_nested_data_is_stored_when_validation_fails(self):
|
| 2144 |
+
class SchemaA(Schema):
|
| 2145 |
+
x = fields.Integer()
|
| 2146 |
+
y = fields.Integer(validate=lambda n: n > 0)
|
| 2147 |
+
z = fields.Integer()
|
| 2148 |
+
|
| 2149 |
+
class SchemaB(Schema):
|
| 2150 |
+
w = fields.Integer()
|
| 2151 |
+
n = fields.Nested(SchemaA)
|
| 2152 |
+
|
| 2153 |
+
sch = SchemaB()
|
| 2154 |
+
|
| 2155 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2156 |
+
sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}})
|
| 2157 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 2158 |
+
assert "z" in errors["n"]
|
| 2159 |
+
assert data == {"w": 90, "n": {"x": 90, "y": 89}}
|
| 2160 |
+
|
| 2161 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2162 |
+
sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}})
|
| 2163 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 2164 |
+
assert "y" in errors["n"]
|
| 2165 |
+
assert data == {"w": 90, "n": {"x": 90, "z": 180}}
|
| 2166 |
+
|
| 2167 |
+
def test_false_value_validation(self):
|
| 2168 |
+
class Sch(Schema):
|
| 2169 |
+
lamb = fields.Raw(validate=lambda x: x is False)
|
| 2170 |
+
equal = fields.Raw(validate=Equal(False))
|
| 2171 |
+
|
| 2172 |
+
errors = Sch().validate({"lamb": False, "equal": False})
|
| 2173 |
+
assert not errors
|
| 2174 |
+
errors = Sch().validate({"lamb": True, "equal": True})
|
| 2175 |
+
assert "lamb" in errors
|
| 2176 |
+
assert errors["lamb"] == ["Invalid value."]
|
| 2177 |
+
assert "equal" in errors
|
| 2178 |
+
assert errors["equal"] == ["Must be equal to False."]
|
| 2179 |
+
|
| 2180 |
+
def test_nested_partial_load(self):
|
| 2181 |
+
class SchemaA(Schema):
|
| 2182 |
+
x = fields.Integer(required=True)
|
| 2183 |
+
y = fields.Integer()
|
| 2184 |
+
|
| 2185 |
+
class SchemaB(Schema):
|
| 2186 |
+
z = fields.Nested(SchemaA)
|
| 2187 |
+
|
| 2188 |
+
b_dict = {"z": {"y": 42}}
|
| 2189 |
+
# Partial loading shouldn't generate any errors.
|
| 2190 |
+
result = SchemaB().load(b_dict, partial=True)
|
| 2191 |
+
assert result["z"]["y"] == 42
|
| 2192 |
+
# Non partial loading should complain about missing values.
|
| 2193 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2194 |
+
SchemaB().load(b_dict)
|
| 2195 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 2196 |
+
assert data["z"]["y"] == 42
|
| 2197 |
+
assert "z" in errors
|
| 2198 |
+
assert "x" in errors["z"]
|
| 2199 |
+
|
| 2200 |
+
def test_deeply_nested_partial_load(self):
|
| 2201 |
+
class SchemaC(Schema):
|
| 2202 |
+
x = fields.Integer(required=True)
|
| 2203 |
+
y = fields.Integer()
|
| 2204 |
+
|
| 2205 |
+
class SchemaB(Schema):
|
| 2206 |
+
c = fields.Nested(SchemaC)
|
| 2207 |
+
|
| 2208 |
+
class SchemaA(Schema):
|
| 2209 |
+
b = fields.Nested(SchemaB)
|
| 2210 |
+
|
| 2211 |
+
a_dict = {"b": {"c": {"y": 42}}}
|
| 2212 |
+
# Partial loading shouldn't generate any errors.
|
| 2213 |
+
result = SchemaA().load(a_dict, partial=True)
|
| 2214 |
+
assert result["b"]["c"]["y"] == 42
|
| 2215 |
+
# Non partial loading should complain about missing values.
|
| 2216 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2217 |
+
SchemaA().load(a_dict)
|
| 2218 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 2219 |
+
assert data["b"]["c"]["y"] == 42
|
| 2220 |
+
assert "b" in errors
|
| 2221 |
+
assert "c" in errors["b"]
|
| 2222 |
+
assert "x" in errors["b"]["c"]
|
| 2223 |
+
|
| 2224 |
+
def test_nested_partial_tuple(self):
|
| 2225 |
+
class SchemaA(Schema):
|
| 2226 |
+
x = fields.Integer(required=True)
|
| 2227 |
+
y = fields.Integer(required=True)
|
| 2228 |
+
|
| 2229 |
+
class SchemaB(Schema):
|
| 2230 |
+
z = fields.Nested(SchemaA)
|
| 2231 |
+
|
| 2232 |
+
b_dict = {"z": {"y": 42}}
|
| 2233 |
+
# If we ignore the missing z.x, z.y should still load.
|
| 2234 |
+
result = SchemaB().load(b_dict, partial=("z.x",))
|
| 2235 |
+
assert result["z"]["y"] == 42
|
| 2236 |
+
# If we ignore a missing z.y we should get a validation error.
|
| 2237 |
+
with pytest.raises(ValidationError):
|
| 2238 |
+
SchemaB().load(b_dict, partial=("z.y",))
|
| 2239 |
+
|
| 2240 |
+
def test_nested_partial_default(self):
|
| 2241 |
+
class SchemaA(Schema):
|
| 2242 |
+
x = fields.Integer(required=True)
|
| 2243 |
+
y = fields.Integer(required=True)
|
| 2244 |
+
|
| 2245 |
+
class SchemaB(Schema):
|
| 2246 |
+
z = fields.Nested(SchemaA(partial=("x",)))
|
| 2247 |
+
|
| 2248 |
+
b_dict = {"z": {"y": 42}}
|
| 2249 |
+
# Nested partial args should be respected.
|
| 2250 |
+
result = SchemaB().load(b_dict)
|
| 2251 |
+
assert result["z"]["y"] == 42
|
| 2252 |
+
with pytest.raises(ValidationError):
|
| 2253 |
+
SchemaB().load({"z": {"x": 0}})
|
| 2254 |
+
|
| 2255 |
+
|
| 2256 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 2257 |
+
def test_required_field_failure(FieldClass): # noqa
|
| 2258 |
+
class RequireSchema(Schema):
|
| 2259 |
+
age = FieldClass(required=True)
|
| 2260 |
+
|
| 2261 |
+
user_data = {"name": "Phil"}
|
| 2262 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2263 |
+
RequireSchema().load(user_data)
|
| 2264 |
+
errors = excinfo.value.messages
|
| 2265 |
+
assert "Missing data for required field." in errors["age"]
|
| 2266 |
+
|
| 2267 |
+
|
| 2268 |
+
@pytest.mark.parametrize(
|
| 2269 |
+
"message",
|
| 2270 |
+
[
|
| 2271 |
+
"My custom required message",
|
| 2272 |
+
{"error": "something", "code": 400},
|
| 2273 |
+
["first error", "second error"],
|
| 2274 |
+
],
|
| 2275 |
+
)
|
| 2276 |
+
def test_required_message_can_be_changed(message):
|
| 2277 |
+
class RequireSchema(Schema):
|
| 2278 |
+
age = fields.Integer(required=True, error_messages={"required": message})
|
| 2279 |
+
|
| 2280 |
+
user_data = {"name": "Phil"}
|
| 2281 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2282 |
+
RequireSchema().load(user_data)
|
| 2283 |
+
errors = excinfo.value.messages
|
| 2284 |
+
expected = [message] if isinstance(message, str) else message
|
| 2285 |
+
assert expected == errors["age"]
|
| 2286 |
+
|
| 2287 |
+
|
| 2288 |
+
@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE))
|
| 2289 |
+
@pytest.mark.parametrize("data", [True, False, 42, None, []])
|
| 2290 |
+
def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown):
|
| 2291 |
+
class MySchema(Schema):
|
| 2292 |
+
foo = fields.Field()
|
| 2293 |
+
bar = fields.Field()
|
| 2294 |
+
|
| 2295 |
+
with pytest.raises(ValidationError, match="Invalid input type.") as excinfo:
|
| 2296 |
+
MySchema(unknown=unknown).load(data)
|
| 2297 |
+
exc = excinfo.value
|
| 2298 |
+
assert list(exc.messages.keys()) == ["_schema"]
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_error_store.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import namedtuple
|
| 2 |
+
|
| 3 |
+
from marshmallow import missing
|
| 4 |
+
from marshmallow.error_store import merge_errors
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_missing_is_falsy():
|
| 8 |
+
assert bool(missing) is False
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
CustomError = namedtuple("CustomError", ["code", "message"])
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestMergeErrors:
|
| 15 |
+
def test_merging_none_and_string(self):
|
| 16 |
+
assert "error1" == merge_errors(None, "error1")
|
| 17 |
+
|
| 18 |
+
def test_merging_none_and_custom_error(self):
|
| 19 |
+
assert CustomError(123, "error1") == merge_errors(
|
| 20 |
+
None, CustomError(123, "error1")
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
def test_merging_none_and_list(self):
|
| 24 |
+
assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"])
|
| 25 |
+
|
| 26 |
+
def test_merging_none_and_dict(self):
|
| 27 |
+
assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"})
|
| 28 |
+
|
| 29 |
+
def test_merging_string_and_none(self):
|
| 30 |
+
assert "error1" == merge_errors("error1", None)
|
| 31 |
+
|
| 32 |
+
def test_merging_custom_error_and_none(self):
|
| 33 |
+
assert CustomError(123, "error1") == merge_errors(
|
| 34 |
+
CustomError(123, "error1"), None
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
def test_merging_list_and_none(self):
|
| 38 |
+
assert ["error1", "error2"] == merge_errors(["error1", "error2"], None)
|
| 39 |
+
|
| 40 |
+
def test_merging_dict_and_none(self):
|
| 41 |
+
assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None)
|
| 42 |
+
|
| 43 |
+
def test_merging_string_and_string(self):
|
| 44 |
+
assert ["error1", "error2"] == merge_errors("error1", "error2")
|
| 45 |
+
|
| 46 |
+
def test_merging_custom_error_and_string(self):
|
| 47 |
+
assert [CustomError(123, "error1"), "error2"] == merge_errors(
|
| 48 |
+
CustomError(123, "error1"), "error2"
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def test_merging_string_and_custom_error(self):
|
| 52 |
+
assert ["error1", CustomError(123, "error2")] == merge_errors(
|
| 53 |
+
"error1", CustomError(123, "error2")
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def test_merging_custom_error_and_custom_error(self):
|
| 57 |
+
assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors(
|
| 58 |
+
CustomError(123, "error1"), CustomError(456, "error2")
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def test_merging_string_and_list(self):
|
| 62 |
+
assert ["error1", "error2"] == merge_errors("error1", ["error2"])
|
| 63 |
+
|
| 64 |
+
def test_merging_string_and_dict(self):
|
| 65 |
+
assert {"_schema": "error1", "field1": "error2"} == merge_errors(
|
| 66 |
+
"error1", {"field1": "error2"}
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
def test_merging_string_and_dict_with_schema_error(self):
|
| 70 |
+
assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors(
|
| 71 |
+
"error1", {"_schema": "error2", "field1": "error3"}
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def test_merging_custom_error_and_list(self):
|
| 75 |
+
assert [CustomError(123, "error1"), "error2"] == merge_errors(
|
| 76 |
+
CustomError(123, "error1"), ["error2"]
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
def test_merging_custom_error_and_dict(self):
|
| 80 |
+
assert {
|
| 81 |
+
"_schema": CustomError(123, "error1"),
|
| 82 |
+
"field1": "error2",
|
| 83 |
+
} == merge_errors(CustomError(123, "error1"), {"field1": "error2"})
|
| 84 |
+
|
| 85 |
+
def test_merging_custom_error_and_dict_with_schema_error(self):
|
| 86 |
+
assert {
|
| 87 |
+
"_schema": [CustomError(123, "error1"), "error2"],
|
| 88 |
+
"field1": "error3",
|
| 89 |
+
} == merge_errors(
|
| 90 |
+
CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"}
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def test_merging_list_and_string(self):
|
| 94 |
+
assert ["error1", "error2"] == merge_errors(["error1"], "error2")
|
| 95 |
+
|
| 96 |
+
def test_merging_list_and_custom_error(self):
|
| 97 |
+
assert ["error1", CustomError(123, "error2")] == merge_errors(
|
| 98 |
+
["error1"], CustomError(123, "error2")
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def test_merging_list_and_list(self):
|
| 102 |
+
assert ["error1", "error2"] == merge_errors(["error1"], ["error2"])
|
| 103 |
+
|
| 104 |
+
def test_merging_list_and_dict(self):
|
| 105 |
+
assert {"_schema": ["error1"], "field1": "error2"} == merge_errors(
|
| 106 |
+
["error1"], {"field1": "error2"}
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
def test_merging_list_and_dict_with_schema_error(self):
|
| 110 |
+
assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors(
|
| 111 |
+
["error1"], {"_schema": "error2", "field1": "error3"}
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
def test_merging_dict_and_string(self):
|
| 115 |
+
assert {"_schema": "error2", "field1": "error1"} == merge_errors(
|
| 116 |
+
{"field1": "error1"}, "error2"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
def test_merging_dict_and_custom_error(self):
|
| 120 |
+
assert {
|
| 121 |
+
"_schema": CustomError(123, "error2"),
|
| 122 |
+
"field1": "error1",
|
| 123 |
+
} == merge_errors({"field1": "error1"}, CustomError(123, "error2"))
|
| 124 |
+
|
| 125 |
+
def test_merging_dict_and_list(self):
|
| 126 |
+
assert {"_schema": ["error2"], "field1": "error1"} == merge_errors(
|
| 127 |
+
{"field1": "error1"}, ["error2"]
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
def test_merging_dict_and_dict(self):
|
| 131 |
+
assert {
|
| 132 |
+
"field1": "error1",
|
| 133 |
+
"field2": ["error2", "error3"],
|
| 134 |
+
"field3": "error4",
|
| 135 |
+
} == merge_errors(
|
| 136 |
+
{"field1": "error1", "field2": "error2"},
|
| 137 |
+
{"field2": "error3", "field3": "error4"},
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def test_deep_merging_dicts(self):
|
| 141 |
+
assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors(
|
| 142 |
+
{"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}}
|
| 143 |
+
)
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_exceptions.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from marshmallow.exceptions import ValidationError
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestValidationError:
|
| 7 |
+
def test_stores_message_in_list(self):
|
| 8 |
+
err = ValidationError("foo")
|
| 9 |
+
assert err.messages == ["foo"]
|
| 10 |
+
|
| 11 |
+
def test_can_pass_list_of_messages(self):
|
| 12 |
+
err = ValidationError(["foo", "bar"])
|
| 13 |
+
assert err.messages == ["foo", "bar"]
|
| 14 |
+
|
| 15 |
+
def test_stores_dictionaries(self):
|
| 16 |
+
messages = {"user": {"email": ["email is invalid"]}}
|
| 17 |
+
err = ValidationError(messages)
|
| 18 |
+
assert err.messages == messages
|
| 19 |
+
|
| 20 |
+
def test_can_store_field_name(self):
|
| 21 |
+
err = ValidationError("invalid email", field_name="email")
|
| 22 |
+
assert err.field_name == "email"
|
| 23 |
+
|
| 24 |
+
def test_str(self):
|
| 25 |
+
err = ValidationError("invalid email")
|
| 26 |
+
assert str(err) == "invalid email"
|
| 27 |
+
|
| 28 |
+
err2 = ValidationError("invalid email", "email")
|
| 29 |
+
assert str(err2) == "invalid email"
|
| 30 |
+
|
| 31 |
+
def test_stores_dictionaries_in_messages_dict(self):
|
| 32 |
+
messages = {"user": {"email": ["email is invalid"]}}
|
| 33 |
+
err = ValidationError(messages)
|
| 34 |
+
assert err.messages_dict == messages
|
| 35 |
+
|
| 36 |
+
def test_messages_dict_type_error_on_badval(self):
|
| 37 |
+
err = ValidationError("foo")
|
| 38 |
+
with pytest.raises(TypeError) as excinfo:
|
| 39 |
+
err.messages_dict # noqa: B018
|
| 40 |
+
assert "cannot access 'messages_dict' when 'messages' is of type list" in str(
|
| 41 |
+
excinfo.value
|
| 42 |
+
)
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_fields.py
ADDED
|
@@ -0,0 +1,665 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from marshmallow import (
|
| 4 |
+
EXCLUDE,
|
| 5 |
+
INCLUDE,
|
| 6 |
+
RAISE,
|
| 7 |
+
Schema,
|
| 8 |
+
ValidationError,
|
| 9 |
+
fields,
|
| 10 |
+
missing,
|
| 11 |
+
)
|
| 12 |
+
from marshmallow.exceptions import StringNotCollectionError
|
| 13 |
+
from marshmallow.orderedset import OrderedSet
|
| 14 |
+
from tests.base import ALL_FIELDS
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.mark.parametrize(
|
| 18 |
+
("alias", "field"),
|
| 19 |
+
[
|
| 20 |
+
(fields.Int, fields.Integer),
|
| 21 |
+
(fields.Str, fields.String),
|
| 22 |
+
(fields.Bool, fields.Boolean),
|
| 23 |
+
(fields.URL, fields.Url),
|
| 24 |
+
],
|
| 25 |
+
)
|
| 26 |
+
def test_field_aliases(alias, field):
|
| 27 |
+
assert alias is field
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestField:
|
| 31 |
+
def test_repr(self):
|
| 32 |
+
default = "œ∑´"
|
| 33 |
+
field = fields.Field(dump_default=default, attribute=None)
|
| 34 |
+
assert repr(field) == (
|
| 35 |
+
f"<fields.Field(dump_default={default!r}, attribute=None, "
|
| 36 |
+
"validate=None, required=False, "
|
| 37 |
+
"load_only=False, dump_only=False, "
|
| 38 |
+
f"load_default={missing}, allow_none=False, "
|
| 39 |
+
f"error_messages={field.error_messages})>"
|
| 40 |
+
)
|
| 41 |
+
int_field = fields.Integer(validate=lambda x: True)
|
| 42 |
+
assert "<fields.Integer" in repr(int_field)
|
| 43 |
+
|
| 44 |
+
def test_error_raised_if_uncallable_validator_passed(self):
|
| 45 |
+
with pytest.raises(ValueError, match="must be a callable"):
|
| 46 |
+
fields.Field(validate="notcallable")
|
| 47 |
+
|
| 48 |
+
def test_error_raised_if_missing_is_set_on_required_field(self):
|
| 49 |
+
with pytest.raises(
|
| 50 |
+
ValueError, match="'load_default' must not be set for required fields"
|
| 51 |
+
):
|
| 52 |
+
fields.Field(required=True, load_default=42)
|
| 53 |
+
|
| 54 |
+
def test_custom_field_receives_attr_and_obj(self):
|
| 55 |
+
class MyField(fields.Field):
|
| 56 |
+
def _deserialize(self, val, attr, data, **kwargs):
|
| 57 |
+
assert attr == "name"
|
| 58 |
+
assert data["foo"] == 42
|
| 59 |
+
return val
|
| 60 |
+
|
| 61 |
+
class MySchema(Schema):
|
| 62 |
+
name = MyField()
|
| 63 |
+
|
| 64 |
+
result = MySchema(unknown=EXCLUDE).load({"name": "Monty", "foo": 42})
|
| 65 |
+
assert result == {"name": "Monty"}
|
| 66 |
+
|
| 67 |
+
def test_custom_field_receives_data_key_if_set(self):
|
| 68 |
+
class MyField(fields.Field):
|
| 69 |
+
def _deserialize(self, val, attr, data, **kwargs):
|
| 70 |
+
assert attr == "name"
|
| 71 |
+
assert data["foo"] == 42
|
| 72 |
+
return val
|
| 73 |
+
|
| 74 |
+
class MySchema(Schema):
|
| 75 |
+
Name = MyField(data_key="name")
|
| 76 |
+
|
| 77 |
+
result = MySchema(unknown=EXCLUDE).load({"name": "Monty", "foo": 42})
|
| 78 |
+
assert result == {"Name": "Monty"}
|
| 79 |
+
|
| 80 |
+
def test_custom_field_follows_data_key_if_set(self):
|
| 81 |
+
class MyField(fields.Field):
|
| 82 |
+
def _serialize(self, val, attr, data):
|
| 83 |
+
assert attr == "name"
|
| 84 |
+
assert data["foo"] == 42
|
| 85 |
+
return val
|
| 86 |
+
|
| 87 |
+
class MySchema(Schema):
|
| 88 |
+
name = MyField(data_key="_NaMe")
|
| 89 |
+
|
| 90 |
+
result = MySchema().dump({"name": "Monty", "foo": 42})
|
| 91 |
+
assert result == {"_NaMe": "Monty"}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class TestParentAndName:
|
| 95 |
+
class MySchema(Schema):
|
| 96 |
+
foo = fields.Field()
|
| 97 |
+
bar = fields.List(fields.Str())
|
| 98 |
+
baz = fields.Tuple([fields.Str(), fields.Int()])
|
| 99 |
+
bax = fields.Mapping(fields.Str(), fields.Int())
|
| 100 |
+
|
| 101 |
+
@pytest.fixture()
|
| 102 |
+
def schema(self):
|
| 103 |
+
return self.MySchema()
|
| 104 |
+
|
| 105 |
+
def test_simple_field_parent_and_name(self, schema):
|
| 106 |
+
assert schema.fields["foo"].parent == schema
|
| 107 |
+
assert schema.fields["foo"].name == "foo"
|
| 108 |
+
assert schema.fields["bar"].parent == schema
|
| 109 |
+
assert schema.fields["bar"].name == "bar"
|
| 110 |
+
|
| 111 |
+
# https://github.com/marshmallow-code/marshmallow/pull/572#issuecomment-275800288
|
| 112 |
+
def test_unbound_field_root_returns_none(self):
|
| 113 |
+
field = fields.Str()
|
| 114 |
+
assert field.root is None
|
| 115 |
+
|
| 116 |
+
inner_field = fields.Nested(self.MySchema())
|
| 117 |
+
outer_field = fields.List(inner_field)
|
| 118 |
+
|
| 119 |
+
assert outer_field.root is None
|
| 120 |
+
assert inner_field.root is None
|
| 121 |
+
|
| 122 |
+
def test_list_field_inner_parent_and_name(self, schema):
|
| 123 |
+
assert schema.fields["bar"].inner.parent == schema.fields["bar"]
|
| 124 |
+
assert schema.fields["bar"].inner.name == "bar"
|
| 125 |
+
|
| 126 |
+
def test_tuple_field_inner_parent_and_name(self, schema):
|
| 127 |
+
for field in schema.fields["baz"].tuple_fields:
|
| 128 |
+
assert field.parent == schema.fields["baz"]
|
| 129 |
+
assert field.name == "baz"
|
| 130 |
+
|
| 131 |
+
def test_mapping_field_inner_parent_and_name(self, schema):
|
| 132 |
+
assert schema.fields["bax"].value_field.parent == schema.fields["bax"]
|
| 133 |
+
assert schema.fields["bax"].value_field.name == "bax"
|
| 134 |
+
assert schema.fields["bax"].key_field.parent == schema.fields["bax"]
|
| 135 |
+
assert schema.fields["bax"].key_field.name == "bax"
|
| 136 |
+
|
| 137 |
+
def test_simple_field_root(self, schema):
|
| 138 |
+
assert schema.fields["foo"].root == schema
|
| 139 |
+
assert schema.fields["bar"].root == schema
|
| 140 |
+
|
| 141 |
+
def test_list_field_inner_root(self, schema):
|
| 142 |
+
assert schema.fields["bar"].inner.root == schema
|
| 143 |
+
|
| 144 |
+
def test_tuple_field_inner_root(self, schema):
|
| 145 |
+
for field in schema.fields["baz"].tuple_fields:
|
| 146 |
+
assert field.root == schema
|
| 147 |
+
|
| 148 |
+
def test_list_root_inheritance(self, schema):
|
| 149 |
+
class OtherSchema(TestParentAndName.MySchema):
|
| 150 |
+
pass
|
| 151 |
+
|
| 152 |
+
schema2 = OtherSchema()
|
| 153 |
+
assert schema.fields["bar"].inner.root == schema
|
| 154 |
+
assert schema2.fields["bar"].inner.root == schema2
|
| 155 |
+
|
| 156 |
+
def test_dict_root_inheritance(self):
|
| 157 |
+
class MySchema(Schema):
|
| 158 |
+
foo = fields.Dict(keys=fields.Str(), values=fields.Int())
|
| 159 |
+
|
| 160 |
+
class OtherSchema(MySchema):
|
| 161 |
+
pass
|
| 162 |
+
|
| 163 |
+
schema = MySchema()
|
| 164 |
+
schema2 = OtherSchema()
|
| 165 |
+
assert schema.fields["foo"].key_field.root == schema
|
| 166 |
+
assert schema.fields["foo"].value_field.root == schema
|
| 167 |
+
assert schema2.fields["foo"].key_field.root == schema2
|
| 168 |
+
assert schema2.fields["foo"].value_field.root == schema2
|
| 169 |
+
|
| 170 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/1357
|
| 171 |
+
def test_datetime_list_inner_format(self, schema):
|
| 172 |
+
class MySchema(Schema):
|
| 173 |
+
foo = fields.List(fields.DateTime())
|
| 174 |
+
bar = fields.Tuple((fields.DateTime(),))
|
| 175 |
+
baz = fields.List(fields.Date())
|
| 176 |
+
qux = fields.Tuple((fields.Date(),))
|
| 177 |
+
|
| 178 |
+
class Meta:
|
| 179 |
+
datetimeformat = "iso8601"
|
| 180 |
+
dateformat = "iso8601"
|
| 181 |
+
|
| 182 |
+
schema = MySchema()
|
| 183 |
+
for field_name in ("foo", "baz"):
|
| 184 |
+
assert schema.fields[field_name].inner.format == "iso8601"
|
| 185 |
+
for field_name in ("bar", "qux"):
|
| 186 |
+
assert schema.fields[field_name].tuple_fields[0].format == "iso8601"
|
| 187 |
+
|
| 188 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/1808
|
| 189 |
+
def test_field_named_parent_has_root(self, schema):
|
| 190 |
+
class MySchema(Schema):
|
| 191 |
+
parent = fields.Field()
|
| 192 |
+
|
| 193 |
+
schema = MySchema()
|
| 194 |
+
assert schema.fields["parent"].root == schema
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class TestMetadata:
|
| 198 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 199 |
+
def test_extra_metadata_may_be_added_to_field(self, FieldClass): # noqa
|
| 200 |
+
with pytest.warns(DeprecationWarning):
|
| 201 |
+
field = FieldClass(description="Just a normal field.")
|
| 202 |
+
assert field.metadata["description"] == "Just a normal field."
|
| 203 |
+
field = FieldClass(
|
| 204 |
+
required=True,
|
| 205 |
+
dump_default=None,
|
| 206 |
+
validate=lambda v: True,
|
| 207 |
+
metadata={"description": "foo", "widget": "select"},
|
| 208 |
+
)
|
| 209 |
+
assert field.metadata == {"description": "foo", "widget": "select"}
|
| 210 |
+
|
| 211 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 212 |
+
def test_field_metadata_added_in_deprecated_style_warns(self, FieldClass): # noqa
|
| 213 |
+
# just the old style
|
| 214 |
+
with pytest.warns(DeprecationWarning):
|
| 215 |
+
field = FieldClass(description="Just a normal field.")
|
| 216 |
+
assert field.metadata["description"] == "Just a normal field."
|
| 217 |
+
# mixed styles
|
| 218 |
+
with pytest.warns(DeprecationWarning):
|
| 219 |
+
field = FieldClass(
|
| 220 |
+
required=True,
|
| 221 |
+
dump_default=None,
|
| 222 |
+
validate=lambda v: True,
|
| 223 |
+
description="foo",
|
| 224 |
+
metadata={"widget": "select"},
|
| 225 |
+
)
|
| 226 |
+
assert field.metadata == {"description": "foo", "widget": "select"}
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class TestDeprecatedDefaultAndMissing:
|
| 230 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 231 |
+
def test_load_default_in_deprecated_style_warns(self, FieldClass):
|
| 232 |
+
# in constructor
|
| 233 |
+
with pytest.warns(
|
| 234 |
+
DeprecationWarning,
|
| 235 |
+
match="The 'missing' argument to fields is deprecated. "
|
| 236 |
+
"Use 'load_default' instead.",
|
| 237 |
+
):
|
| 238 |
+
FieldClass(missing=None)
|
| 239 |
+
|
| 240 |
+
# via attribute
|
| 241 |
+
myfield = FieldClass(load_default=1)
|
| 242 |
+
with pytest.warns(
|
| 243 |
+
DeprecationWarning,
|
| 244 |
+
match="The 'missing' attribute of fields is deprecated. "
|
| 245 |
+
"Use 'load_default' instead.",
|
| 246 |
+
):
|
| 247 |
+
assert myfield.missing == 1
|
| 248 |
+
with pytest.warns(
|
| 249 |
+
DeprecationWarning,
|
| 250 |
+
match="The 'missing' attribute of fields is deprecated. "
|
| 251 |
+
"Use 'load_default' instead.",
|
| 252 |
+
):
|
| 253 |
+
myfield.missing = 0
|
| 254 |
+
# but setting it worked
|
| 255 |
+
assert myfield.load_default == 0
|
| 256 |
+
|
| 257 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 258 |
+
def test_dump_default_in_deprecated_style_warns(self, FieldClass):
|
| 259 |
+
# in constructor
|
| 260 |
+
with pytest.warns(
|
| 261 |
+
DeprecationWarning,
|
| 262 |
+
match="The 'default' argument to fields is deprecated. "
|
| 263 |
+
"Use 'dump_default' instead.",
|
| 264 |
+
):
|
| 265 |
+
FieldClass(default=None)
|
| 266 |
+
|
| 267 |
+
# via attribute
|
| 268 |
+
myfield = FieldClass(dump_default=1)
|
| 269 |
+
with pytest.warns(
|
| 270 |
+
DeprecationWarning,
|
| 271 |
+
match="The 'default' attribute of fields is deprecated. "
|
| 272 |
+
"Use 'dump_default' instead.",
|
| 273 |
+
):
|
| 274 |
+
assert myfield.default == 1
|
| 275 |
+
with pytest.warns(
|
| 276 |
+
DeprecationWarning,
|
| 277 |
+
match="The 'default' attribute of fields is deprecated. "
|
| 278 |
+
"Use 'dump_default' instead.",
|
| 279 |
+
):
|
| 280 |
+
myfield.default = 0
|
| 281 |
+
# but setting it worked
|
| 282 |
+
assert myfield.dump_default == 0
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class TestErrorMessages:
|
| 286 |
+
class MyField(fields.Field):
|
| 287 |
+
default_error_messages = {"custom": "Custom error message."}
|
| 288 |
+
|
| 289 |
+
error_messages = [
|
| 290 |
+
("required", "Missing data for required field."),
|
| 291 |
+
("null", "Field may not be null."),
|
| 292 |
+
("custom", "Custom error message."),
|
| 293 |
+
("validator_failed", "Invalid value."),
|
| 294 |
+
]
|
| 295 |
+
|
| 296 |
+
def test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg(
|
| 297 |
+
self,
|
| 298 |
+
):
|
| 299 |
+
field = self.MyField()
|
| 300 |
+
assert field.error_messages["custom"] == "Custom error message."
|
| 301 |
+
assert "required" in field.error_messages
|
| 302 |
+
|
| 303 |
+
def test_default_error_messages_get_merged_with_parent_error_messages(self):
|
| 304 |
+
field = self.MyField(error_messages={"passed": "Passed error message"})
|
| 305 |
+
assert field.error_messages["passed"] == "Passed error message"
|
| 306 |
+
|
| 307 |
+
@pytest.mark.parametrize(("key", "message"), error_messages)
|
| 308 |
+
def test_make_error(self, key, message):
|
| 309 |
+
field = self.MyField()
|
| 310 |
+
|
| 311 |
+
error = field.make_error(key)
|
| 312 |
+
assert error.args[0] == message
|
| 313 |
+
|
| 314 |
+
@pytest.mark.parametrize(("key", "message"), error_messages)
|
| 315 |
+
def test_fail(self, key, message):
|
| 316 |
+
field = self.MyField()
|
| 317 |
+
|
| 318 |
+
with pytest.warns(DeprecationWarning):
|
| 319 |
+
try:
|
| 320 |
+
field.fail(key)
|
| 321 |
+
except ValidationError as error:
|
| 322 |
+
assert error.args[0] == message
|
| 323 |
+
|
| 324 |
+
def test_make_error_key_doesnt_exist(self):
|
| 325 |
+
with pytest.raises(AssertionError) as excinfo:
|
| 326 |
+
self.MyField().make_error("doesntexist")
|
| 327 |
+
assert "doesntexist" in excinfo.value.args[0]
|
| 328 |
+
assert "MyField" in excinfo.value.args[0]
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class TestNestedField:
|
| 332 |
+
@pytest.mark.parametrize("param", ("only", "exclude"))
|
| 333 |
+
def test_nested_only_and_exclude_as_string(self, param):
|
| 334 |
+
with pytest.raises(StringNotCollectionError):
|
| 335 |
+
fields.Nested(Schema, **{param: "foo"})
|
| 336 |
+
|
| 337 |
+
@pytest.mark.parametrize(
|
| 338 |
+
"nested_value",
|
| 339 |
+
[
|
| 340 |
+
{"hello": fields.String()},
|
| 341 |
+
lambda: {"hello": fields.String()},
|
| 342 |
+
],
|
| 343 |
+
)
|
| 344 |
+
def test_nested_instantiation_from_dict(self, nested_value):
|
| 345 |
+
class MySchema(Schema):
|
| 346 |
+
nested = fields.Nested(nested_value)
|
| 347 |
+
|
| 348 |
+
schema = MySchema()
|
| 349 |
+
|
| 350 |
+
ret = schema.load({"nested": {"hello": "world"}})
|
| 351 |
+
assert ret == {"nested": {"hello": "world"}}
|
| 352 |
+
|
| 353 |
+
with pytest.raises(ValidationError):
|
| 354 |
+
schema.load({"nested": {"x": 1}})
|
| 355 |
+
|
| 356 |
+
@pytest.mark.parametrize("schema_unknown", (EXCLUDE, INCLUDE, RAISE))
|
| 357 |
+
@pytest.mark.parametrize("field_unknown", (None, EXCLUDE, INCLUDE, RAISE))
|
| 358 |
+
def test_nested_unknown_override(self, schema_unknown, field_unknown):
|
| 359 |
+
class NestedSchema(Schema):
|
| 360 |
+
class Meta:
|
| 361 |
+
unknown = schema_unknown
|
| 362 |
+
|
| 363 |
+
class MySchema(Schema):
|
| 364 |
+
nested = fields.Nested(NestedSchema, unknown=field_unknown)
|
| 365 |
+
|
| 366 |
+
if field_unknown == EXCLUDE or (
|
| 367 |
+
schema_unknown == EXCLUDE and not field_unknown
|
| 368 |
+
):
|
| 369 |
+
assert MySchema().load({"nested": {"x": 1}}) == {"nested": {}}
|
| 370 |
+
elif field_unknown == INCLUDE or (
|
| 371 |
+
schema_unknown == INCLUDE and not field_unknown
|
| 372 |
+
):
|
| 373 |
+
assert MySchema().load({"nested": {"x": 1}}) == {"nested": {"x": 1}}
|
| 374 |
+
elif field_unknown == RAISE or (schema_unknown == RAISE and not field_unknown):
|
| 375 |
+
with pytest.raises(ValidationError):
|
| 376 |
+
MySchema().load({"nested": {"x": 1}})
|
| 377 |
+
|
| 378 |
+
@pytest.mark.parametrize(
|
| 379 |
+
("param", "fields_list"), [("only", ["foo"]), ("exclude", ["bar"])]
|
| 380 |
+
)
|
| 381 |
+
def test_nested_schema_only_and_exclude(self, param, fields_list):
|
| 382 |
+
class NestedSchema(Schema):
|
| 383 |
+
# We mean to test the use of OrderedSet to specify it explicitly
|
| 384 |
+
# even if it is default
|
| 385 |
+
set_class = OrderedSet
|
| 386 |
+
foo = fields.String()
|
| 387 |
+
bar = fields.String()
|
| 388 |
+
|
| 389 |
+
class MySchema(Schema):
|
| 390 |
+
nested = fields.Nested(NestedSchema(), **{param: fields_list})
|
| 391 |
+
|
| 392 |
+
assert MySchema().dump({"nested": {"foo": "baz", "bar": "bax"}}) == {
|
| 393 |
+
"nested": {"foo": "baz"}
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
class TestListNested:
|
| 398 |
+
@pytest.mark.parametrize("param", ("only", "exclude", "dump_only", "load_only"))
|
| 399 |
+
def test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested(
|
| 400 |
+
self, param
|
| 401 |
+
):
|
| 402 |
+
class Child(Schema):
|
| 403 |
+
name = fields.String()
|
| 404 |
+
age = fields.Integer()
|
| 405 |
+
|
| 406 |
+
class Family(Schema):
|
| 407 |
+
children = fields.List(fields.Nested(Child))
|
| 408 |
+
|
| 409 |
+
schema = Family(**{param: ["children.name"]})
|
| 410 |
+
assert getattr(schema.fields["children"].inner.schema, param) == {"name"}
|
| 411 |
+
|
| 412 |
+
@pytest.mark.parametrize(
|
| 413 |
+
("param", "expected_attribute", "expected_dump"),
|
| 414 |
+
(
|
| 415 |
+
("only", {"name"}, {"children": [{"name": "Lily"}]}),
|
| 416 |
+
("exclude", {"name", "surname", "age"}, {"children": [{}]}),
|
| 417 |
+
),
|
| 418 |
+
)
|
| 419 |
+
def test_list_nested_class_only_and_exclude_merged_with_nested(
|
| 420 |
+
self, param, expected_attribute, expected_dump
|
| 421 |
+
):
|
| 422 |
+
class Child(Schema):
|
| 423 |
+
name = fields.String()
|
| 424 |
+
surname = fields.String()
|
| 425 |
+
age = fields.Integer()
|
| 426 |
+
|
| 427 |
+
class Family(Schema):
|
| 428 |
+
children = fields.List(fields.Nested(Child, **{param: ("name", "surname")}))
|
| 429 |
+
|
| 430 |
+
schema = Family(**{param: ["children.name", "children.age"]})
|
| 431 |
+
assert getattr(schema.fields["children"].inner, param) == expected_attribute
|
| 432 |
+
|
| 433 |
+
family = {"children": [{"name": "Lily", "surname": "Martinez", "age": 15}]}
|
| 434 |
+
assert schema.dump(family) == expected_dump
|
| 435 |
+
|
| 436 |
+
def test_list_nested_class_multiple_dumps(self):
|
| 437 |
+
class Child(Schema):
|
| 438 |
+
name = fields.String()
|
| 439 |
+
surname = fields.String()
|
| 440 |
+
age = fields.Integer()
|
| 441 |
+
|
| 442 |
+
class Family(Schema):
|
| 443 |
+
children = fields.List(fields.Nested(Child, only=("name", "age")))
|
| 444 |
+
|
| 445 |
+
family = {"children": [{"name": "Lily", "surname": "Martinez", "age": 15}]}
|
| 446 |
+
assert Family(only=("children.age",)).dump(family) == {
|
| 447 |
+
"children": [{"age": 15}]
|
| 448 |
+
}
|
| 449 |
+
assert Family(only=("children.name",)).dump(family) == {
|
| 450 |
+
"children": [{"name": "Lily"}]
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
@pytest.mark.parametrize(
|
| 454 |
+
("param", "expected_attribute", "expected_dump"),
|
| 455 |
+
(
|
| 456 |
+
("only", {"name"}, {"children": [{"name": "Lily"}]}),
|
| 457 |
+
("exclude", {"name", "surname", "age"}, {"children": [{}]}),
|
| 458 |
+
),
|
| 459 |
+
)
|
| 460 |
+
def test_list_nested_instance_only_and_exclude_merged_with_nested(
|
| 461 |
+
self, param, expected_attribute, expected_dump
|
| 462 |
+
):
|
| 463 |
+
class Child(Schema):
|
| 464 |
+
name = fields.String()
|
| 465 |
+
surname = fields.String()
|
| 466 |
+
age = fields.Integer()
|
| 467 |
+
|
| 468 |
+
class Family(Schema):
|
| 469 |
+
children = fields.List(fields.Nested(Child(**{param: ("name", "surname")})))
|
| 470 |
+
|
| 471 |
+
schema = Family(**{param: ["children.name", "children.age"]})
|
| 472 |
+
assert (
|
| 473 |
+
getattr(schema.fields["children"].inner.schema, param) == expected_attribute
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
family = {"children": [{"name": "Lily", "surname": "Martinez", "age": 15}]}
|
| 477 |
+
assert schema.dump(family) == expected_dump
|
| 478 |
+
|
| 479 |
+
def test_list_nested_instance_multiple_dumps(self):
|
| 480 |
+
class Child(Schema):
|
| 481 |
+
name = fields.String()
|
| 482 |
+
surname = fields.String()
|
| 483 |
+
age = fields.Integer()
|
| 484 |
+
|
| 485 |
+
class Family(Schema):
|
| 486 |
+
children = fields.List(fields.Nested(Child(only=("name", "age"))))
|
| 487 |
+
|
| 488 |
+
family = {"children": [{"name": "Lily", "surname": "Martinez", "age": 15}]}
|
| 489 |
+
assert Family(only=("children.age",)).dump(family) == {
|
| 490 |
+
"children": [{"age": 15}]
|
| 491 |
+
}
|
| 492 |
+
assert Family(only=("children.name",)).dump(family) == {
|
| 493 |
+
"children": [{"name": "Lily"}]
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
@pytest.mark.parametrize(
|
| 497 |
+
("param", "expected_attribute", "expected_dump"),
|
| 498 |
+
(
|
| 499 |
+
("only", {"name"}, {"children": [{"name": "Lily"}]}),
|
| 500 |
+
("exclude", {"name", "surname", "age"}, {"children": [{}]}),
|
| 501 |
+
),
|
| 502 |
+
)
|
| 503 |
+
def test_list_nested_lambda_only_and_exclude_merged_with_nested(
|
| 504 |
+
self, param, expected_attribute, expected_dump
|
| 505 |
+
):
|
| 506 |
+
class Child(Schema):
|
| 507 |
+
name = fields.String()
|
| 508 |
+
surname = fields.String()
|
| 509 |
+
age = fields.Integer()
|
| 510 |
+
|
| 511 |
+
class Family(Schema):
|
| 512 |
+
children = fields.List(
|
| 513 |
+
fields.Nested(lambda: Child(**{param: ("name", "surname")}))
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
schema = Family(**{param: ["children.name", "children.age"]})
|
| 517 |
+
assert (
|
| 518 |
+
getattr(schema.fields["children"].inner.schema, param) == expected_attribute
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
family = {"children": [{"name": "Lily", "surname": "Martinez", "age": 15}]}
|
| 522 |
+
assert schema.dump(family) == expected_dump
|
| 523 |
+
|
| 524 |
+
def test_list_nested_partial_propagated_to_nested(self):
|
| 525 |
+
class Child(Schema):
|
| 526 |
+
name = fields.String(required=True)
|
| 527 |
+
age = fields.Integer(required=True)
|
| 528 |
+
|
| 529 |
+
class Family(Schema):
|
| 530 |
+
children = fields.List(fields.Nested(Child))
|
| 531 |
+
|
| 532 |
+
payload = {"children": [{"name": "Lucette"}]}
|
| 533 |
+
|
| 534 |
+
for val in (True, ("children.age",)):
|
| 535 |
+
result = Family(partial=val).load(payload)
|
| 536 |
+
assert result["children"][0]["name"] == "Lucette"
|
| 537 |
+
result = Family().load(payload, partial=val)
|
| 538 |
+
assert result["children"][0]["name"] == "Lucette"
|
| 539 |
+
|
| 540 |
+
for val in (False, ("children.name",)):
|
| 541 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 542 |
+
result = Family(partial=val).load(payload)
|
| 543 |
+
assert excinfo.value.args[0] == {
|
| 544 |
+
"children": {0: {"age": ["Missing data for required field."]}}
|
| 545 |
+
}
|
| 546 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 547 |
+
result = Family().load(payload, partial=val)
|
| 548 |
+
assert excinfo.value.args[0] == {
|
| 549 |
+
"children": {0: {"age": ["Missing data for required field."]}}
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
class TestTupleNested:
|
| 554 |
+
@pytest.mark.parametrize("param", ("dump_only", "load_only"))
|
| 555 |
+
def test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested(
|
| 556 |
+
self, param
|
| 557 |
+
):
|
| 558 |
+
class Child(Schema):
|
| 559 |
+
name = fields.String()
|
| 560 |
+
age = fields.Integer()
|
| 561 |
+
|
| 562 |
+
class Family(Schema):
|
| 563 |
+
children = fields.Tuple((fields.Nested(Child), fields.Nested(Child)))
|
| 564 |
+
|
| 565 |
+
schema = Family(**{param: ["children.name"]})
|
| 566 |
+
assert getattr(schema.fields["children"].tuple_fields[0].schema, param) == {
|
| 567 |
+
"name"
|
| 568 |
+
}
|
| 569 |
+
assert getattr(schema.fields["children"].tuple_fields[1].schema, param) == {
|
| 570 |
+
"name"
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
def test_tuple_nested_partial_propagated_to_nested(self):
|
| 574 |
+
class Child(Schema):
|
| 575 |
+
name = fields.String(required=True)
|
| 576 |
+
age = fields.Integer(required=True)
|
| 577 |
+
|
| 578 |
+
class Family(Schema):
|
| 579 |
+
children = fields.Tuple((fields.Nested(Child),))
|
| 580 |
+
|
| 581 |
+
payload = {"children": [{"name": "Lucette"}]}
|
| 582 |
+
|
| 583 |
+
for val in (True, ("children.age",)):
|
| 584 |
+
result = Family(partial=val).load(payload)
|
| 585 |
+
assert result["children"][0]["name"] == "Lucette"
|
| 586 |
+
result = Family().load(payload, partial=val)
|
| 587 |
+
assert result["children"][0]["name"] == "Lucette"
|
| 588 |
+
|
| 589 |
+
for val in (False, ("children.name",)):
|
| 590 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 591 |
+
result = Family(partial=val).load(payload)
|
| 592 |
+
assert excinfo.value.args[0] == {
|
| 593 |
+
"children": {0: {"age": ["Missing data for required field."]}}
|
| 594 |
+
}
|
| 595 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 596 |
+
result = Family().load(payload, partial=val)
|
| 597 |
+
assert excinfo.value.args[0] == {
|
| 598 |
+
"children": {0: {"age": ["Missing data for required field."]}}
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
class TestDictNested:
|
| 603 |
+
@pytest.mark.parametrize("param", ("only", "exclude", "dump_only", "load_only"))
|
| 604 |
+
def test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested(
|
| 605 |
+
self, param
|
| 606 |
+
):
|
| 607 |
+
class Child(Schema):
|
| 608 |
+
name = fields.String()
|
| 609 |
+
age = fields.Integer()
|
| 610 |
+
|
| 611 |
+
class Family(Schema):
|
| 612 |
+
children = fields.Dict(values=fields.Nested(Child))
|
| 613 |
+
|
| 614 |
+
schema = Family(**{param: ["children.name"]})
|
| 615 |
+
assert getattr(schema.fields["children"].value_field.schema, param) == {"name"}
|
| 616 |
+
|
| 617 |
+
@pytest.mark.parametrize(
|
| 618 |
+
("param", "expected"),
|
| 619 |
+
(("only", {"name"}), ("exclude", {"name", "surname", "age"})),
|
| 620 |
+
)
|
| 621 |
+
def test_dict_nested_only_and_exclude_merged_with_nested(self, param, expected):
|
| 622 |
+
class Child(Schema):
|
| 623 |
+
name = fields.String()
|
| 624 |
+
surname = fields.String()
|
| 625 |
+
age = fields.Integer()
|
| 626 |
+
|
| 627 |
+
class Family(Schema):
|
| 628 |
+
children = fields.Dict(
|
| 629 |
+
values=fields.Nested(Child, **{param: ("name", "surname")})
|
| 630 |
+
)
|
| 631 |
+
|
| 632 |
+
schema = Family(**{param: ["children.name", "children.age"]})
|
| 633 |
+
assert getattr(schema.fields["children"].value_field, param) == expected
|
| 634 |
+
|
| 635 |
+
def test_dict_nested_partial_propagated_to_nested(self):
|
| 636 |
+
class Child(Schema):
|
| 637 |
+
name = fields.String(required=True)
|
| 638 |
+
age = fields.Integer(required=True)
|
| 639 |
+
|
| 640 |
+
class Family(Schema):
|
| 641 |
+
children = fields.Dict(values=fields.Nested(Child))
|
| 642 |
+
|
| 643 |
+
payload = {"children": {"daughter": {"name": "Lucette"}}}
|
| 644 |
+
|
| 645 |
+
for val in (True, ("children.age",)):
|
| 646 |
+
result = Family(partial=val).load(payload)
|
| 647 |
+
assert result["children"]["daughter"]["name"] == "Lucette"
|
| 648 |
+
result = Family().load(payload, partial=val)
|
| 649 |
+
assert result["children"]["daughter"]["name"] == "Lucette"
|
| 650 |
+
|
| 651 |
+
for val in (False, ("children.name",)):
|
| 652 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 653 |
+
result = Family(partial=val).load(payload)
|
| 654 |
+
assert excinfo.value.args[0] == {
|
| 655 |
+
"children": {
|
| 656 |
+
"daughter": {"value": {"age": ["Missing data for required field."]}}
|
| 657 |
+
}
|
| 658 |
+
}
|
| 659 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 660 |
+
result = Family().load(payload, partial=val)
|
| 661 |
+
assert excinfo.value.args[0] == {
|
| 662 |
+
"children": {
|
| 663 |
+
"daughter": {"value": {"age": ["Missing data for required field."]}}
|
| 664 |
+
}
|
| 665 |
+
}
|
tasks/marshmallow-code__marshmallow.9716f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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime as dt
|
| 2 |
+
from collections import OrderedDict
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from marshmallow import EXCLUDE, Schema, fields
|
| 7 |
+
from tests.base import User
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestUnordered:
|
| 11 |
+
class UnorderedSchema(Schema):
|
| 12 |
+
name = fields.Str()
|
| 13 |
+
email = fields.Str()
|
| 14 |
+
|
| 15 |
+
class Meta:
|
| 16 |
+
ordered = False
|
| 17 |
+
|
| 18 |
+
def test_unordered_dump_returns_dict(self):
|
| 19 |
+
schema = self.UnorderedSchema()
|
| 20 |
+
u = User("steve", email="steve@steve.steve")
|
| 21 |
+
result = schema.dump(u)
|
| 22 |
+
assert not isinstance(result, OrderedDict)
|
| 23 |
+
assert type(result) is dict
|
| 24 |
+
|
| 25 |
+
def test_unordered_load_returns_dict(self):
|
| 26 |
+
schema = self.UnorderedSchema()
|
| 27 |
+
result = schema.load({"name": "steve", "email": "steve@steve.steve"})
|
| 28 |
+
assert not isinstance(result, OrderedDict)
|
| 29 |
+
assert type(result) is dict
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class KeepOrder(Schema):
|
| 33 |
+
class Meta:
|
| 34 |
+
ordered = True
|
| 35 |
+
|
| 36 |
+
name = fields.String(allow_none=True)
|
| 37 |
+
email = fields.Email(allow_none=True)
|
| 38 |
+
age = fields.Integer()
|
| 39 |
+
created = fields.DateTime()
|
| 40 |
+
id = fields.Integer(allow_none=True)
|
| 41 |
+
homepage = fields.Url()
|
| 42 |
+
birthdate = fields.Date()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class OrderedMetaSchema(Schema):
|
| 46 |
+
id = fields.Int(allow_none=True)
|
| 47 |
+
email = fields.Email(allow_none=True)
|
| 48 |
+
|
| 49 |
+
class Meta:
|
| 50 |
+
fields = ("name", "email", "age", "created", "id", "homepage", "birthdate")
|
| 51 |
+
ordered = True
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class OrderedNestedOnly(Schema):
|
| 55 |
+
class Meta:
|
| 56 |
+
ordered = True
|
| 57 |
+
|
| 58 |
+
user = fields.Nested(KeepOrder)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class TestFieldOrdering:
|
| 62 |
+
@pytest.mark.parametrize("with_meta", (False, True))
|
| 63 |
+
def test_ordered_option_is_inherited(self, user, with_meta):
|
| 64 |
+
class ParentUnordered(Schema):
|
| 65 |
+
class Meta:
|
| 66 |
+
ordered = False
|
| 67 |
+
|
| 68 |
+
# KeepOrder is before ParentUnordered in MRO,
|
| 69 |
+
# so ChildOrderedSchema will be ordered
|
| 70 |
+
class ChildOrderedSchema(KeepOrder, ParentUnordered):
|
| 71 |
+
if with_meta:
|
| 72 |
+
|
| 73 |
+
class Meta:
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
schema = ChildOrderedSchema()
|
| 77 |
+
assert schema.opts.ordered is True
|
| 78 |
+
assert schema.dict_class == OrderedDict
|
| 79 |
+
|
| 80 |
+
data = schema.dump(user)
|
| 81 |
+
keys = list(data)
|
| 82 |
+
assert keys == [
|
| 83 |
+
"name",
|
| 84 |
+
"email",
|
| 85 |
+
"age",
|
| 86 |
+
"created",
|
| 87 |
+
"id",
|
| 88 |
+
"homepage",
|
| 89 |
+
"birthdate",
|
| 90 |
+
]
|
| 91 |
+
|
| 92 |
+
# KeepOrder is before ParentUnordered in MRO,
|
| 93 |
+
# so ChildOrderedSchema will be ordered
|
| 94 |
+
class ChildUnorderedSchema(ParentUnordered, KeepOrder):
|
| 95 |
+
class Meta:
|
| 96 |
+
pass
|
| 97 |
+
|
| 98 |
+
schema = ChildUnorderedSchema()
|
| 99 |
+
assert schema.opts.ordered is False
|
| 100 |
+
|
| 101 |
+
def test_ordering_is_off_by_default(self):
|
| 102 |
+
class DummySchema(Schema):
|
| 103 |
+
pass
|
| 104 |
+
|
| 105 |
+
schema = DummySchema()
|
| 106 |
+
assert schema.ordered is False
|
| 107 |
+
|
| 108 |
+
def test_declared_field_order_is_maintained_on_dump(self, user):
|
| 109 |
+
ser = KeepOrder()
|
| 110 |
+
data = ser.dump(user)
|
| 111 |
+
keys = list(data)
|
| 112 |
+
assert keys == [
|
| 113 |
+
"name",
|
| 114 |
+
"email",
|
| 115 |
+
"age",
|
| 116 |
+
"created",
|
| 117 |
+
"id",
|
| 118 |
+
"homepage",
|
| 119 |
+
"birthdate",
|
| 120 |
+
]
|
| 121 |
+
|
| 122 |
+
def test_declared_field_order_is_maintained_on_load(self, serialized_user):
|
| 123 |
+
schema = KeepOrder(unknown=EXCLUDE)
|
| 124 |
+
data = schema.load(serialized_user)
|
| 125 |
+
keys = list(data)
|
| 126 |
+
assert keys == [
|
| 127 |
+
"name",
|
| 128 |
+
"email",
|
| 129 |
+
"age",
|
| 130 |
+
"created",
|
| 131 |
+
"id",
|
| 132 |
+
"homepage",
|
| 133 |
+
"birthdate",
|
| 134 |
+
]
|
| 135 |
+
|
| 136 |
+
def test_nested_field_order_with_only_arg_is_maintained_on_dump(self, user):
|
| 137 |
+
schema = OrderedNestedOnly()
|
| 138 |
+
data = schema.dump({"user": user})
|
| 139 |
+
user_data = data["user"]
|
| 140 |
+
keys = list(user_data)
|
| 141 |
+
assert keys == [
|
| 142 |
+
"name",
|
| 143 |
+
"email",
|
| 144 |
+
"age",
|
| 145 |
+
"created",
|
| 146 |
+
"id",
|
| 147 |
+
"homepage",
|
| 148 |
+
"birthdate",
|
| 149 |
+
]
|
| 150 |
+
|
| 151 |
+
def test_nested_field_order_with_only_arg_is_maintained_on_load(self):
|
| 152 |
+
schema = OrderedNestedOnly()
|
| 153 |
+
data = schema.load(
|
| 154 |
+
{
|
| 155 |
+
"user": {
|
| 156 |
+
"name": "Foo",
|
| 157 |
+
"email": "Foo@bar.com",
|
| 158 |
+
"age": 42,
|
| 159 |
+
"created": dt.datetime.now().isoformat(),
|
| 160 |
+
"id": 123,
|
| 161 |
+
"homepage": "http://foo.com",
|
| 162 |
+
"birthdate": dt.datetime.now().date().isoformat(),
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
)
|
| 166 |
+
user_data = data["user"]
|
| 167 |
+
keys = list(user_data)
|
| 168 |
+
assert keys == [
|
| 169 |
+
"name",
|
| 170 |
+
"email",
|
| 171 |
+
"age",
|
| 172 |
+
"created",
|
| 173 |
+
"id",
|
| 174 |
+
"homepage",
|
| 175 |
+
"birthdate",
|
| 176 |
+
]
|
| 177 |
+
|
| 178 |
+
def test_nested_field_order_with_exclude_arg_is_maintained(self, user):
|
| 179 |
+
class HasNestedExclude(Schema):
|
| 180 |
+
user = fields.Nested(KeepOrder, exclude=("birthdate",))
|
| 181 |
+
|
| 182 |
+
ser = HasNestedExclude()
|
| 183 |
+
data = ser.dump({"user": user})
|
| 184 |
+
user_data = data["user"]
|
| 185 |
+
keys = list(user_data)
|
| 186 |
+
assert keys == ["name", "email", "age", "created", "id", "homepage"]
|
| 187 |
+
|
| 188 |
+
def test_meta_fields_order_is_maintained_on_dump(self, user):
|
| 189 |
+
ser = OrderedMetaSchema()
|
| 190 |
+
data = ser.dump(user)
|
| 191 |
+
keys = list(data)
|
| 192 |
+
assert keys == [
|
| 193 |
+
"name",
|
| 194 |
+
"email",
|
| 195 |
+
"age",
|
| 196 |
+
"created",
|
| 197 |
+
"id",
|
| 198 |
+
"homepage",
|
| 199 |
+
"birthdate",
|
| 200 |
+
]
|
| 201 |
+
|
| 202 |
+
def test_meta_fields_order_is_maintained_on_load(self, serialized_user):
|
| 203 |
+
schema = OrderedMetaSchema(unknown=EXCLUDE)
|
| 204 |
+
data = schema.load(serialized_user)
|
| 205 |
+
keys = list(data)
|
| 206 |
+
assert keys == [
|
| 207 |
+
"name",
|
| 208 |
+
"email",
|
| 209 |
+
"age",
|
| 210 |
+
"created",
|
| 211 |
+
"id",
|
| 212 |
+
"homepage",
|
| 213 |
+
"birthdate",
|
| 214 |
+
]
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class TestIncludeOption:
|
| 218 |
+
class AddFieldsSchema(Schema):
|
| 219 |
+
name = fields.Str()
|
| 220 |
+
|
| 221 |
+
class Meta:
|
| 222 |
+
include = {"from": fields.Str()}
|
| 223 |
+
|
| 224 |
+
def test_fields_are_added(self):
|
| 225 |
+
s = self.AddFieldsSchema()
|
| 226 |
+
in_data = {"name": "Steve", "from": "Oskosh"}
|
| 227 |
+
result = s.load({"name": "Steve", "from": "Oskosh"})
|
| 228 |
+
assert result == in_data
|
| 229 |
+
|
| 230 |
+
def test_included_fields_ordered_after_declared_fields(self):
|
| 231 |
+
class AddFieldsOrdered(Schema):
|
| 232 |
+
name = fields.Str()
|
| 233 |
+
email = fields.Str()
|
| 234 |
+
|
| 235 |
+
class Meta:
|
| 236 |
+
include = {
|
| 237 |
+
"from": fields.Str(),
|
| 238 |
+
"in": fields.Str(),
|
| 239 |
+
"@at": fields.Str(),
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
s = AddFieldsOrdered()
|
| 243 |
+
in_data = {
|
| 244 |
+
"name": "Steve",
|
| 245 |
+
"from": "Oskosh",
|
| 246 |
+
"email": "steve@steve.steve",
|
| 247 |
+
"in": "VA",
|
| 248 |
+
"@at": "Charlottesville",
|
| 249 |
+
}
|
| 250 |
+
# declared fields, then "included" fields
|
| 251 |
+
expected_fields = ["name", "email", "from", "in", "@at"]
|
| 252 |
+
assert list(AddFieldsOrdered._declared_fields.keys()) == expected_fields
|
| 253 |
+
|
| 254 |
+
result = s.load(in_data)
|
| 255 |
+
assert list(result.keys()) == expected_fields
|
| 256 |
+
|
| 257 |
+
def test_added_fields_are_inherited(self):
|
| 258 |
+
class AddFieldsChild(self.AddFieldsSchema):
|
| 259 |
+
email = fields.Str()
|
| 260 |
+
|
| 261 |
+
s = AddFieldsChild()
|
| 262 |
+
assert "email" in s._declared_fields.keys()
|
| 263 |
+
assert "from" in s._declared_fields.keys()
|
| 264 |
+
assert isinstance(s._declared_fields["from"], fields.Str)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class TestManyOption:
|
| 268 |
+
class ManySchema(Schema):
|
| 269 |
+
foo = fields.Str()
|
| 270 |
+
|
| 271 |
+
class Meta:
|
| 272 |
+
many = True
|
| 273 |
+
|
| 274 |
+
def test_many_by_default(self):
|
| 275 |
+
test = self.ManySchema()
|
| 276 |
+
assert test.load([{"foo": "bar"}]) == [{"foo": "bar"}]
|
| 277 |
+
|
| 278 |
+
def test_explicit_single(self):
|
| 279 |
+
test = self.ManySchema(many=False)
|
| 280 |
+
assert test.load({"foo": "bar"}) == {"foo": "bar"}
|
tasks/marshmallow-code__marsh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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from marshmallow import Schema, class_registry, fields
|
| 4 |
+
from marshmallow.exceptions import RegistryError
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_serializer_has_class_registry():
|
| 8 |
+
class MySchema(Schema):
|
| 9 |
+
pass
|
| 10 |
+
|
| 11 |
+
class MySubSchema(Schema):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
assert "MySchema" in class_registry._registry
|
| 15 |
+
assert "MySubSchema" in class_registry._registry
|
| 16 |
+
|
| 17 |
+
# by fullpath
|
| 18 |
+
assert "tests.test_registry.MySchema" in class_registry._registry
|
| 19 |
+
assert "tests.test_registry.MySubSchema" in class_registry._registry
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_register_class_meta_option():
|
| 23 |
+
class UnregisteredSchema(Schema):
|
| 24 |
+
class Meta:
|
| 25 |
+
register = False
|
| 26 |
+
|
| 27 |
+
class RegisteredSchema(Schema):
|
| 28 |
+
class Meta:
|
| 29 |
+
register = True
|
| 30 |
+
|
| 31 |
+
class RegisteredOverrideSchema(UnregisteredSchema):
|
| 32 |
+
class Meta:
|
| 33 |
+
register = True
|
| 34 |
+
|
| 35 |
+
class UnregisteredOverrideSchema(RegisteredSchema):
|
| 36 |
+
class Meta:
|
| 37 |
+
register = False
|
| 38 |
+
|
| 39 |
+
assert "UnregisteredSchema" not in class_registry._registry
|
| 40 |
+
assert "tests.test_registry.UnregisteredSchema" not in class_registry._registry
|
| 41 |
+
|
| 42 |
+
assert "RegisteredSchema" in class_registry._registry
|
| 43 |
+
assert "tests.test_registry.RegisteredSchema" in class_registry._registry
|
| 44 |
+
|
| 45 |
+
assert "RegisteredOverrideSchema" in class_registry._registry
|
| 46 |
+
assert "tests.test_registry.RegisteredOverrideSchema" in class_registry._registry
|
| 47 |
+
|
| 48 |
+
assert "UnregisteredOverrideSchema" not in class_registry._registry
|
| 49 |
+
assert (
|
| 50 |
+
"tests.test_registry.UnregisteredOverrideSchema" not in class_registry._registry
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_serializer_class_registry_register_same_classname_different_module():
|
| 55 |
+
reglen = len(class_registry._registry)
|
| 56 |
+
|
| 57 |
+
type("MyTestRegSchema", (Schema,), {"__module__": "modA"})
|
| 58 |
+
|
| 59 |
+
assert "MyTestRegSchema" in class_registry._registry
|
| 60 |
+
assert len(class_registry._registry.get("MyTestRegSchema")) == 1
|
| 61 |
+
assert "modA.MyTestRegSchema" in class_registry._registry
|
| 62 |
+
# storing for classname and fullpath
|
| 63 |
+
assert len(class_registry._registry) == reglen + 2
|
| 64 |
+
|
| 65 |
+
type("MyTestRegSchema", (Schema,), {"__module__": "modB"})
|
| 66 |
+
|
| 67 |
+
assert "MyTestRegSchema" in class_registry._registry
|
| 68 |
+
# aggregating classes with same name from different modules
|
| 69 |
+
assert len(class_registry._registry.get("MyTestRegSchema")) == 2
|
| 70 |
+
assert "modB.MyTestRegSchema" in class_registry._registry
|
| 71 |
+
# storing for same classname (+0) and different module (+1)
|
| 72 |
+
assert len(class_registry._registry) == reglen + 2 + 1
|
| 73 |
+
|
| 74 |
+
type("MyTestRegSchema", (Schema,), {"__module__": "modB"})
|
| 75 |
+
|
| 76 |
+
assert "MyTestRegSchema" in class_registry._registry
|
| 77 |
+
# only the class with matching module has been replaced
|
| 78 |
+
assert len(class_registry._registry.get("MyTestRegSchema")) == 2
|
| 79 |
+
assert "modB.MyTestRegSchema" in class_registry._registry
|
| 80 |
+
# only the class with matching module has been replaced (+0)
|
| 81 |
+
assert len(class_registry._registry) == reglen + 2 + 1
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_serializer_class_registry_override_if_same_classname_same_module():
|
| 85 |
+
reglen = len(class_registry._registry)
|
| 86 |
+
|
| 87 |
+
type("MyTestReg2Schema", (Schema,), {"__module__": "SameModulePath"})
|
| 88 |
+
|
| 89 |
+
assert "MyTestReg2Schema" in class_registry._registry
|
| 90 |
+
assert len(class_registry._registry.get("MyTestReg2Schema")) == 1
|
| 91 |
+
assert "SameModulePath.MyTestReg2Schema" in class_registry._registry
|
| 92 |
+
assert len(class_registry._registry.get("SameModulePath.MyTestReg2Schema")) == 1
|
| 93 |
+
# storing for classname and fullpath
|
| 94 |
+
assert len(class_registry._registry) == reglen + 2
|
| 95 |
+
|
| 96 |
+
type("MyTestReg2Schema", (Schema,), {"__module__": "SameModulePath"})
|
| 97 |
+
|
| 98 |
+
assert "MyTestReg2Schema" in class_registry._registry
|
| 99 |
+
# overriding same class name and same module
|
| 100 |
+
assert len(class_registry._registry.get("MyTestReg2Schema")) == 1
|
| 101 |
+
assert "SameModulePath.MyTestReg2Schema" in class_registry._registry
|
| 102 |
+
# overriding same fullpath
|
| 103 |
+
assert len(class_registry._registry.get("SameModulePath.MyTestReg2Schema")) == 1
|
| 104 |
+
# overriding for same classname (+0) and different module (+0)
|
| 105 |
+
assert len(class_registry._registry) == reglen + 2
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class A:
|
| 109 |
+
def __init__(self, _id, b=None):
|
| 110 |
+
self.id = _id
|
| 111 |
+
self.b = b
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class B:
|
| 115 |
+
def __init__(self, _id, a=None):
|
| 116 |
+
self.id = _id
|
| 117 |
+
self.a = a
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class C:
|
| 121 |
+
def __init__(self, _id, bs=None):
|
| 122 |
+
self.id = _id
|
| 123 |
+
self.bs = bs or []
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class ASchema(Schema):
|
| 127 |
+
id = fields.Integer()
|
| 128 |
+
b = fields.Nested("tests.test_registry.BSchema", exclude=("a",))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class BSchema(Schema):
|
| 132 |
+
id = fields.Integer()
|
| 133 |
+
a = fields.Nested("tests.test_registry.ASchema")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class CSchema(Schema):
|
| 137 |
+
id = fields.Integer()
|
| 138 |
+
bs = fields.Nested("tests.test_registry.BSchema", many=True)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_two_way_nesting():
|
| 142 |
+
a_obj = A(1)
|
| 143 |
+
b_obj = B(2, a=a_obj)
|
| 144 |
+
a_obj.b = b_obj
|
| 145 |
+
|
| 146 |
+
a_serialized = ASchema().dump(a_obj)
|
| 147 |
+
b_serialized = BSchema().dump(b_obj)
|
| 148 |
+
assert a_serialized["b"]["id"] == b_obj.id
|
| 149 |
+
assert b_serialized["a"]["id"] == a_obj.id
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def test_nesting_with_class_name_many():
|
| 153 |
+
c_obj = C(1, bs=[B(2), B(3), B(4)])
|
| 154 |
+
|
| 155 |
+
c_serialized = CSchema().dump(c_obj)
|
| 156 |
+
|
| 157 |
+
assert len(c_serialized["bs"]) == len(c_obj.bs)
|
| 158 |
+
assert c_serialized["bs"][0]["id"] == c_obj.bs[0].id
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_invalid_class_name_in_nested_field_raises_error(user):
|
| 162 |
+
class MySchema(Schema):
|
| 163 |
+
nf = fields.Nested("notfound")
|
| 164 |
+
|
| 165 |
+
sch = MySchema()
|
| 166 |
+
msg = "Class with name {!r} was not found".format("notfound")
|
| 167 |
+
with pytest.raises(RegistryError, match=msg):
|
| 168 |
+
sch.dump({"nf": None})
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class FooSerializer(Schema):
|
| 172 |
+
_id = fields.Integer()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def test_multiple_classes_with_same_name_raises_error():
|
| 176 |
+
# Import a class with the same name
|
| 177 |
+
from .foo_serializer import FooSerializer as FooSerializer1 # noqa
|
| 178 |
+
|
| 179 |
+
class MySchema(Schema):
|
| 180 |
+
foo = fields.Nested("FooSerializer")
|
| 181 |
+
|
| 182 |
+
# Using a nested field with the class name fails because there are
|
| 183 |
+
# two defined classes with the same name
|
| 184 |
+
sch = MySchema()
|
| 185 |
+
msg = "Multiple classes with name {!r} were found.".format("FooSerializer")
|
| 186 |
+
with pytest.raises(RegistryError, match=msg):
|
| 187 |
+
sch.dump({"foo": {"_id": 1}})
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_multiple_classes_with_all():
|
| 191 |
+
# Import a class with the same name
|
| 192 |
+
from .foo_serializer import FooSerializer as FooSerializer1 # noqa
|
| 193 |
+
|
| 194 |
+
classes = class_registry.get_class("FooSerializer", all=True)
|
| 195 |
+
assert len(classes) == 2
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def test_can_use_full_module_path_to_class():
|
| 199 |
+
from .foo_serializer import FooSerializer as FooSerializer1 # noqa
|
| 200 |
+
|
| 201 |
+
# Using full paths is ok
|
| 202 |
+
|
| 203 |
+
class Schema1(Schema):
|
| 204 |
+
foo = fields.Nested("tests.foo_serializer.FooSerializer")
|
| 205 |
+
|
| 206 |
+
sch = Schema1()
|
| 207 |
+
|
| 208 |
+
# Note: The arguments here don't matter. What matters is that no
|
| 209 |
+
# error is raised
|
| 210 |
+
assert sch.dump({"foo": {"_id": 42}})
|
| 211 |
+
|
| 212 |
+
class Schema2(Schema):
|
| 213 |
+
foo = fields.Nested("tests.test_registry.FooSerializer")
|
| 214 |
+
|
| 215 |
+
sch = Schema2()
|
| 216 |
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime as dt
|
| 2 |
+
import decimal
|
| 3 |
+
import math
|
| 4 |
+
import random
|
| 5 |
+
from collections import OrderedDict, namedtuple
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
import simplejson as json
|
| 9 |
+
|
| 10 |
+
from marshmallow import (
|
| 11 |
+
EXCLUDE,
|
| 12 |
+
INCLUDE,
|
| 13 |
+
RAISE,
|
| 14 |
+
Schema,
|
| 15 |
+
class_registry,
|
| 16 |
+
fields,
|
| 17 |
+
utils,
|
| 18 |
+
validates,
|
| 19 |
+
validates_schema,
|
| 20 |
+
)
|
| 21 |
+
from marshmallow.exceptions import (
|
| 22 |
+
RegistryError,
|
| 23 |
+
StringNotCollectionError,
|
| 24 |
+
ValidationError,
|
| 25 |
+
)
|
| 26 |
+
from tests.base import (
|
| 27 |
+
Blog,
|
| 28 |
+
BlogOnlySchema,
|
| 29 |
+
BlogSchema,
|
| 30 |
+
BlogSchemaExclude,
|
| 31 |
+
BlogSchemaMeta,
|
| 32 |
+
BlogUserMetaSchema,
|
| 33 |
+
ExtendedUserSchema,
|
| 34 |
+
User,
|
| 35 |
+
UserAdditionalSchema,
|
| 36 |
+
UserExcludeSchema,
|
| 37 |
+
UserFloatStringSchema,
|
| 38 |
+
UserIntSchema,
|
| 39 |
+
UserMetaSchema,
|
| 40 |
+
UserRelativeUrlSchema,
|
| 41 |
+
UserSchema,
|
| 42 |
+
mockjson,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
random.seed(1)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# Run tests with both verbose serializer and 'meta' option serializer
|
| 49 |
+
@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema])
|
| 50 |
+
def test_serializing_basic_object(SchemaClass, user):
|
| 51 |
+
s = SchemaClass()
|
| 52 |
+
data = s.dump(user)
|
| 53 |
+
assert data["name"] == user.name
|
| 54 |
+
assert math.isclose(data["age"], 42.3)
|
| 55 |
+
assert data["registered"]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_serializer_dump(user):
|
| 59 |
+
s = UserSchema()
|
| 60 |
+
result = s.dump(user)
|
| 61 |
+
assert result["name"] == user.name
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_load_resets_errors():
|
| 65 |
+
class MySchema(Schema):
|
| 66 |
+
email = fields.Email()
|
| 67 |
+
|
| 68 |
+
schema = MySchema()
|
| 69 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 70 |
+
schema.load({"name": "Joe", "email": "notvalid"})
|
| 71 |
+
errors = excinfo.value.messages
|
| 72 |
+
assert len(errors["email"]) == 1
|
| 73 |
+
assert "Not a valid email address." in errors["email"][0]
|
| 74 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 75 |
+
schema.load({"name": "Joe", "email": "__invalid"})
|
| 76 |
+
errors = excinfo.value.messages
|
| 77 |
+
assert len(errors["email"]) == 1
|
| 78 |
+
assert "Not a valid email address." in errors["email"][0]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_load_validation_error_stores_input_data_and_valid_data():
|
| 82 |
+
class MySchema(Schema):
|
| 83 |
+
always_valid = fields.DateTime()
|
| 84 |
+
always_invalid = fields.Field(validate=[lambda v: False])
|
| 85 |
+
|
| 86 |
+
schema = MySchema()
|
| 87 |
+
input_data = {
|
| 88 |
+
"always_valid": dt.datetime.now(dt.timezone.utc).isoformat(),
|
| 89 |
+
"always_invalid": 24,
|
| 90 |
+
}
|
| 91 |
+
try:
|
| 92 |
+
schema.load(input_data)
|
| 93 |
+
except ValidationError as err:
|
| 94 |
+
# err.data is the raw input data
|
| 95 |
+
assert err.data == input_data
|
| 96 |
+
assert "always_valid" in err.valid_data
|
| 97 |
+
# err.valid_data contains valid, deserialized data
|
| 98 |
+
assert isinstance(err.valid_data["always_valid"], dt.datetime)
|
| 99 |
+
# excludes invalid data
|
| 100 |
+
assert "always_invalid" not in err.valid_data
|
| 101 |
+
else:
|
| 102 |
+
pytest.fail("Data is invalid. Expected a ValidationError to be raised.")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def test_load_resets_error_fields():
|
| 106 |
+
class MySchema(Schema):
|
| 107 |
+
email = fields.Email()
|
| 108 |
+
name = fields.Str()
|
| 109 |
+
|
| 110 |
+
schema = MySchema()
|
| 111 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 112 |
+
schema.load({"name": "Joe", "email": "not-valid"})
|
| 113 |
+
exc = excinfo.value
|
| 114 |
+
assert len(exc.messages.keys()) == 1
|
| 115 |
+
|
| 116 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 117 |
+
schema.load({"name": 12, "email": "mick@stones.com"})
|
| 118 |
+
exc = excinfo.value
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def test_errored_fields_do_not_appear_in_output():
|
| 122 |
+
class MyField(fields.Field):
|
| 123 |
+
# Make sure validation fails during serialization
|
| 124 |
+
def _serialize(self, val, attr, obj):
|
| 125 |
+
raise ValidationError("oops")
|
| 126 |
+
|
| 127 |
+
class MySchema(Schema):
|
| 128 |
+
foo = MyField(validate=lambda x: False)
|
| 129 |
+
|
| 130 |
+
sch = MySchema()
|
| 131 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 132 |
+
sch.load({"foo": 2})
|
| 133 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 134 |
+
|
| 135 |
+
assert "foo" in errors
|
| 136 |
+
assert "foo" not in data
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_load_many_stores_error_indices():
|
| 140 |
+
s = UserSchema()
|
| 141 |
+
data = [
|
| 142 |
+
{"name": "Mick", "email": "mick@stones.com"},
|
| 143 |
+
{"name": "Keith", "email": "invalid-email", "homepage": "invalid-homepage"},
|
| 144 |
+
]
|
| 145 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 146 |
+
s.load(data, many=True)
|
| 147 |
+
errors = excinfo.value.messages
|
| 148 |
+
assert 0 not in errors
|
| 149 |
+
assert 1 in errors
|
| 150 |
+
assert "email" in errors[1]
|
| 151 |
+
assert "homepage" in errors[1]
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def test_dump_many():
|
| 155 |
+
s = UserSchema()
|
| 156 |
+
u1, u2 = User("Mick"), User("Keith")
|
| 157 |
+
data = s.dump([u1, u2], many=True)
|
| 158 |
+
assert len(data) == 2
|
| 159 |
+
assert data[0] == s.dump(u1)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@pytest.mark.parametrize("value", [[], {}, [1], {1: 1}])
|
| 163 |
+
def test_boolean_can_dump_unhashable(value):
|
| 164 |
+
class MySchema(Schema):
|
| 165 |
+
has_items = fields.Boolean()
|
| 166 |
+
|
| 167 |
+
schema = MySchema()
|
| 168 |
+
data = schema.dump({"has_items": value})
|
| 169 |
+
assert data["has_items"] is bool(value)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def test_multiple_errors_can_be_stored_for_a_given_index():
|
| 173 |
+
class MySchema(Schema):
|
| 174 |
+
foo = fields.Str(validate=lambda x: len(x) > 3)
|
| 175 |
+
bar = fields.Int(validate=lambda x: x > 3)
|
| 176 |
+
|
| 177 |
+
sch = MySchema()
|
| 178 |
+
valid = {"foo": "loll", "bar": 42}
|
| 179 |
+
invalid = {"foo": "lol", "bar": 3}
|
| 180 |
+
errors = sch.validate([valid, invalid], many=True)
|
| 181 |
+
|
| 182 |
+
assert 1 in errors
|
| 183 |
+
assert len(errors[1]) == 2
|
| 184 |
+
assert "foo" in errors[1]
|
| 185 |
+
assert "bar" in errors[1]
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def test_dump_returns_a_dict(user):
|
| 189 |
+
s = UserSchema()
|
| 190 |
+
result = s.dump(user)
|
| 191 |
+
assert type(result) is dict
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def test_dumps_returns_a_string(user):
|
| 195 |
+
s = UserSchema()
|
| 196 |
+
result = s.dumps(user)
|
| 197 |
+
assert type(result) is str
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def test_dumping_single_object_with_collection_schema(user):
|
| 201 |
+
s = UserSchema(many=True)
|
| 202 |
+
result = s.dump(user, many=False)
|
| 203 |
+
assert type(result) is dict
|
| 204 |
+
assert result == UserSchema().dump(user)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def test_loading_single_object_with_collection_schema():
|
| 208 |
+
s = UserSchema(many=True)
|
| 209 |
+
in_data = {"name": "Mick", "email": "mick@stones.com"}
|
| 210 |
+
result = s.load(in_data, many=False)
|
| 211 |
+
assert type(result) is User
|
| 212 |
+
assert result.name == UserSchema().load(in_data).name
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def test_dumps_many():
|
| 216 |
+
s = UserSchema()
|
| 217 |
+
u1, u2 = User("Mick"), User("Keith")
|
| 218 |
+
json_result = s.dumps([u1, u2], many=True)
|
| 219 |
+
data = json.loads(json_result)
|
| 220 |
+
assert len(data) == 2
|
| 221 |
+
assert data[0] == s.dump(u1)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def test_load_returns_an_object():
|
| 225 |
+
s = UserSchema()
|
| 226 |
+
result = s.load({"name": "Monty"})
|
| 227 |
+
assert type(result) is User
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def test_load_many():
|
| 231 |
+
s = UserSchema()
|
| 232 |
+
in_data = [{"name": "Mick"}, {"name": "Keith"}]
|
| 233 |
+
result = s.load(in_data, many=True)
|
| 234 |
+
assert type(result) is list
|
| 235 |
+
assert type(result[0]) is User
|
| 236 |
+
assert result[0].name == "Mick"
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol"))
|
| 240 |
+
def test_load_invalid_input_type(val):
|
| 241 |
+
class Sch(Schema):
|
| 242 |
+
name = fields.Str()
|
| 243 |
+
|
| 244 |
+
with pytest.raises(ValidationError) as e:
|
| 245 |
+
Sch().load(val)
|
| 246 |
+
assert e.value.messages == {"_schema": ["Invalid input type."]}
|
| 247 |
+
assert e.value.valid_data == {}
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/906
|
| 251 |
+
@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol"))
|
| 252 |
+
def test_load_many_invalid_input_type(val):
|
| 253 |
+
class Sch(Schema):
|
| 254 |
+
name = fields.Str()
|
| 255 |
+
|
| 256 |
+
with pytest.raises(ValidationError) as e:
|
| 257 |
+
Sch(many=True).load(val)
|
| 258 |
+
assert e.value.messages == {"_schema": ["Invalid input type."]}
|
| 259 |
+
assert e.value.valid_data == []
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@pytest.mark.parametrize("val", ([], set()))
|
| 263 |
+
def test_load_many_empty_collection(val):
|
| 264 |
+
class Sch(Schema):
|
| 265 |
+
name = fields.Str()
|
| 266 |
+
|
| 267 |
+
assert Sch(many=True).load(val) == []
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol"))
|
| 271 |
+
def test_load_many_in_nested_invalid_input_type(val):
|
| 272 |
+
class Inner(Schema):
|
| 273 |
+
name = fields.String()
|
| 274 |
+
|
| 275 |
+
class Outer(Schema):
|
| 276 |
+
list1 = fields.List(fields.Nested(Inner))
|
| 277 |
+
list2 = fields.Nested(Inner, many=True)
|
| 278 |
+
|
| 279 |
+
with pytest.raises(ValidationError) as e:
|
| 280 |
+
Outer().load({"list1": val, "list2": val})
|
| 281 |
+
# TODO: Error messages should be identical (#779)
|
| 282 |
+
assert e.value.messages == {
|
| 283 |
+
"list1": ["Not a valid list."],
|
| 284 |
+
"list2": ["Invalid type."],
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@pytest.mark.parametrize("val", ([], set()))
|
| 289 |
+
def test_load_many_in_nested_empty_collection(val):
|
| 290 |
+
class Inner(Schema):
|
| 291 |
+
name = fields.String()
|
| 292 |
+
|
| 293 |
+
class Outer(Schema):
|
| 294 |
+
list1 = fields.List(fields.Nested(Inner))
|
| 295 |
+
list2 = fields.Nested(Inner, many=True)
|
| 296 |
+
|
| 297 |
+
assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []}
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def test_loads_returns_a_user():
|
| 301 |
+
s = UserSchema()
|
| 302 |
+
result = s.loads(json.dumps({"name": "Monty"}))
|
| 303 |
+
assert type(result) is User
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def test_loads_many():
|
| 307 |
+
s = UserSchema()
|
| 308 |
+
in_data = [{"name": "Mick"}, {"name": "Keith"}]
|
| 309 |
+
in_json_data = json.dumps(in_data)
|
| 310 |
+
result = s.loads(in_json_data, many=True)
|
| 311 |
+
assert type(result) is list
|
| 312 |
+
assert result[0].name == "Mick"
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def test_loads_deserializes_from_json():
|
| 316 |
+
user_dict = {"name": "Monty", "age": "42.3"}
|
| 317 |
+
user_json = json.dumps(user_dict)
|
| 318 |
+
result = UserSchema().loads(user_json)
|
| 319 |
+
assert isinstance(result, User)
|
| 320 |
+
assert result.name == "Monty"
|
| 321 |
+
assert math.isclose(result.age, 42.3)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def test_serializing_none():
|
| 325 |
+
class MySchema(Schema):
|
| 326 |
+
id = fields.Str(dump_default="no-id")
|
| 327 |
+
num = fields.Int()
|
| 328 |
+
name = fields.Str()
|
| 329 |
+
|
| 330 |
+
data = UserSchema().dump(None)
|
| 331 |
+
assert data == {"id": "no-id"}
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def test_default_many_symmetry():
|
| 335 |
+
"""The dump/load(s) methods should all default to the many value of the schema."""
|
| 336 |
+
s_many = UserSchema(many=True, only=("name",))
|
| 337 |
+
s_single = UserSchema(only=("name",))
|
| 338 |
+
u1, u2 = User("King Arthur"), User("Sir Lancelot")
|
| 339 |
+
s_single.load(s_single.dump(u1))
|
| 340 |
+
s_single.loads(s_single.dumps(u1))
|
| 341 |
+
s_many.load(s_many.dump([u1, u2]))
|
| 342 |
+
s_many.loads(s_many.dumps([u1, u2]))
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def test_on_bind_field_hook():
|
| 346 |
+
class MySchema(Schema):
|
| 347 |
+
foo = fields.Str()
|
| 348 |
+
|
| 349 |
+
def on_bind_field(self, field_name, field_obj):
|
| 350 |
+
assert field_obj.parent is self
|
| 351 |
+
field_obj.metadata["fname"] = field_name
|
| 352 |
+
|
| 353 |
+
schema = MySchema()
|
| 354 |
+
assert schema.fields["foo"].metadata["fname"] == "foo"
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def test_nested_on_bind_field_hook():
|
| 358 |
+
class MySchema(Schema):
|
| 359 |
+
class NestedSchema(Schema):
|
| 360 |
+
bar = fields.Str()
|
| 361 |
+
|
| 362 |
+
def on_bind_field(self, field_name, field_obj):
|
| 363 |
+
field_obj.metadata["fname"] = self.context["fname"]
|
| 364 |
+
|
| 365 |
+
foo = fields.Nested(NestedSchema)
|
| 366 |
+
|
| 367 |
+
schema1 = MySchema(context={"fname": "foobar"})
|
| 368 |
+
schema2 = MySchema(context={"fname": "quxquux"})
|
| 369 |
+
|
| 370 |
+
assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar"
|
| 371 |
+
assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux"
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class TestValidate:
|
| 375 |
+
def test_validate_raises_with_errors_dict(self):
|
| 376 |
+
s = UserSchema()
|
| 377 |
+
errors = s.validate({"email": "bad-email", "name": "Valid Name"})
|
| 378 |
+
assert type(errors) is dict
|
| 379 |
+
assert "email" in errors
|
| 380 |
+
assert "name" not in errors
|
| 381 |
+
|
| 382 |
+
valid_data = {"name": "Valid Name", "email": "valid@email.com"}
|
| 383 |
+
errors = s.validate(valid_data)
|
| 384 |
+
assert errors == {}
|
| 385 |
+
|
| 386 |
+
def test_validate_many(self):
|
| 387 |
+
s = UserSchema(many=True)
|
| 388 |
+
in_data = [
|
| 389 |
+
{"name": "Valid Name", "email": "validemail@hotmail.com"},
|
| 390 |
+
{"name": "Valid Name2", "email": "invalid"},
|
| 391 |
+
]
|
| 392 |
+
errors = s.validate(in_data, many=True)
|
| 393 |
+
assert 1 in errors
|
| 394 |
+
assert "email" in errors[1]
|
| 395 |
+
|
| 396 |
+
def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self):
|
| 397 |
+
class NoIndex(Schema):
|
| 398 |
+
email = fields.Email()
|
| 399 |
+
|
| 400 |
+
class Meta:
|
| 401 |
+
index_errors = False
|
| 402 |
+
|
| 403 |
+
s = NoIndex()
|
| 404 |
+
in_data = [
|
| 405 |
+
{"name": "Valid Name", "email": "validemail@hotmail.com"},
|
| 406 |
+
{"name": "Valid Name2", "email": "invalid"},
|
| 407 |
+
]
|
| 408 |
+
errors = s.validate(in_data, many=True)
|
| 409 |
+
assert 1 not in errors
|
| 410 |
+
assert "email" in errors
|
| 411 |
+
|
| 412 |
+
def test_validate(self):
|
| 413 |
+
s = UserSchema()
|
| 414 |
+
errors = s.validate({"email": "bad-email"})
|
| 415 |
+
assert errors == {"email": ["Not a valid email address."]}
|
| 416 |
+
|
| 417 |
+
def test_validate_required(self):
|
| 418 |
+
class MySchema(Schema):
|
| 419 |
+
foo = fields.Field(required=True)
|
| 420 |
+
|
| 421 |
+
s = MySchema()
|
| 422 |
+
errors = s.validate({"bar": 42})
|
| 423 |
+
assert "foo" in errors
|
| 424 |
+
assert "required" in errors["foo"][0]
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema])
|
| 428 |
+
def test_fields_are_not_copies(SchemaClass):
|
| 429 |
+
s = SchemaClass()
|
| 430 |
+
s2 = SchemaClass()
|
| 431 |
+
assert s.fields is not s2.fields
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def test_dumps_returns_json(user):
|
| 435 |
+
ser = UserSchema()
|
| 436 |
+
serialized = ser.dump(user)
|
| 437 |
+
json_data = ser.dumps(user)
|
| 438 |
+
assert type(json_data) is str
|
| 439 |
+
expected = json.dumps(serialized)
|
| 440 |
+
assert json_data == expected
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def test_naive_datetime_field(user, serialized_user):
|
| 444 |
+
expected = utils.isoformat(user.created)
|
| 445 |
+
assert serialized_user["created"] == expected
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def test_datetime_formatted_field(user, serialized_user):
|
| 449 |
+
result = serialized_user["created_formatted"]
|
| 450 |
+
assert result == user.created.strftime("%Y-%m-%d")
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def test_datetime_iso_field(user, serialized_user):
|
| 454 |
+
assert serialized_user["created_iso"] == utils.isoformat(user.created)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def test_tz_datetime_field(user, serialized_user):
|
| 458 |
+
# Datetime is corrected back to GMT
|
| 459 |
+
expected = utils.isoformat(user.updated)
|
| 460 |
+
assert serialized_user["updated"] == expected
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def test_class_variable(serialized_user):
|
| 464 |
+
assert serialized_user["species"] == "Homo sapiens"
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema])
|
| 468 |
+
def test_serialize_many(SchemaClass):
|
| 469 |
+
user1 = User(name="Mick", age=123)
|
| 470 |
+
user2 = User(name="Keith", age=456)
|
| 471 |
+
users = [user1, user2]
|
| 472 |
+
serialized = SchemaClass(many=True).dump(users)
|
| 473 |
+
assert len(serialized) == 2
|
| 474 |
+
assert serialized[0]["name"] == "Mick"
|
| 475 |
+
assert serialized[1]["name"] == "Keith"
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def test_inheriting_schema(user):
|
| 479 |
+
sch = ExtendedUserSchema()
|
| 480 |
+
result = sch.dump(user)
|
| 481 |
+
assert result["name"] == user.name
|
| 482 |
+
user.is_old = True
|
| 483 |
+
result = sch.dump(user)
|
| 484 |
+
assert result["is_old"] is True
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def test_custom_field(serialized_user, user):
|
| 488 |
+
assert serialized_user["uppername"] == user.name.upper()
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def test_url_field(serialized_user, user):
|
| 492 |
+
assert serialized_user["homepage"] == user.homepage
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def test_relative_url_field():
|
| 496 |
+
u = {"name": "John", "homepage": "/foo"}
|
| 497 |
+
UserRelativeUrlSchema().load(u)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema])
|
| 501 |
+
def test_stores_invalid_url_error(SchemaClass):
|
| 502 |
+
user = {"name": "Steve", "homepage": "www.foo.com"}
|
| 503 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 504 |
+
SchemaClass().load(user)
|
| 505 |
+
errors = excinfo.value.messages
|
| 506 |
+
assert "homepage" in errors
|
| 507 |
+
expected = ["Not a valid URL."]
|
| 508 |
+
assert errors["homepage"] == expected
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema])
|
| 512 |
+
def test_email_field(SchemaClass):
|
| 513 |
+
u = User("John", email="john@example.com")
|
| 514 |
+
s = SchemaClass().dump(u)
|
| 515 |
+
assert s["email"] == "john@example.com"
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def test_stored_invalid_email():
|
| 519 |
+
u = {"name": "John", "email": "johnexample.com"}
|
| 520 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 521 |
+
UserSchema().load(u)
|
| 522 |
+
errors = excinfo.value.messages
|
| 523 |
+
assert "email" in errors
|
| 524 |
+
assert errors["email"][0] == "Not a valid email address."
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def test_integer_field():
|
| 528 |
+
u = User("John", age=42.3)
|
| 529 |
+
serialized = UserIntSchema().dump(u)
|
| 530 |
+
assert type(serialized["age"]) is int
|
| 531 |
+
assert serialized["age"] == 42
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def test_as_string():
|
| 535 |
+
u = User("John", age=42.3)
|
| 536 |
+
serialized = UserFloatStringSchema().dump(u)
|
| 537 |
+
assert type(serialized["age"]) is str
|
| 538 |
+
assert math.isclose(float(serialized["age"]), 42.3)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema])
|
| 542 |
+
def test_method_field(SchemaClass, serialized_user):
|
| 543 |
+
assert serialized_user["is_old"] is False
|
| 544 |
+
u = User("Joe", age=81)
|
| 545 |
+
assert SchemaClass().dump(u)["is_old"] is True
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
def test_function_field(serialized_user, user):
|
| 549 |
+
assert serialized_user["lowername"] == user.name.lower()
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def test_fields_must_be_declared_as_instances(user):
|
| 553 |
+
class BadUserSchema(Schema):
|
| 554 |
+
name = fields.String
|
| 555 |
+
|
| 556 |
+
with pytest.raises(
|
| 557 |
+
TypeError, match='Field for "name" must be declared as a Field instance'
|
| 558 |
+
):
|
| 559 |
+
BadUserSchema().dump(user)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
# regression test
|
| 563 |
+
def test_bind_field_does_not_swallow_typeerror():
|
| 564 |
+
class MySchema(Schema):
|
| 565 |
+
name = fields.Str()
|
| 566 |
+
|
| 567 |
+
def on_bind_field(self, field_name, field_obj):
|
| 568 |
+
raise TypeError("boom")
|
| 569 |
+
|
| 570 |
+
with pytest.raises(TypeError, match="boom"):
|
| 571 |
+
MySchema()
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema])
|
| 575 |
+
def test_serializing_generator(SchemaClass):
|
| 576 |
+
users = [User("Foo"), User("Bar")]
|
| 577 |
+
user_gen = (u for u in users)
|
| 578 |
+
s = SchemaClass(many=True).dump(user_gen)
|
| 579 |
+
assert len(s) == 2
|
| 580 |
+
assert s[0] == SchemaClass().dump(users[0])
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def test_serializing_empty_list_returns_empty_list():
|
| 584 |
+
assert UserSchema(many=True).dump([]) == []
|
| 585 |
+
assert UserMetaSchema(many=True).dump([]) == []
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
def test_serializing_dict():
|
| 589 |
+
user = {
|
| 590 |
+
"name": "foo",
|
| 591 |
+
"email": "foo@bar.com",
|
| 592 |
+
"age": 42,
|
| 593 |
+
"various_data": {"foo": "bar"},
|
| 594 |
+
}
|
| 595 |
+
data = UserSchema().dump(user)
|
| 596 |
+
assert data["name"] == "foo"
|
| 597 |
+
assert data["age"] == 42
|
| 598 |
+
assert data["various_data"] == {"foo": "bar"}
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def test_serializing_dict_with_meta_fields():
|
| 602 |
+
class MySchema(Schema):
|
| 603 |
+
class Meta:
|
| 604 |
+
fields = ("foo", "bar")
|
| 605 |
+
|
| 606 |
+
sch = MySchema()
|
| 607 |
+
data = sch.dump({"foo": 42, "bar": 24, "baz": 424})
|
| 608 |
+
assert data["foo"] == 42
|
| 609 |
+
assert data["bar"] == 24
|
| 610 |
+
assert "baz" not in data
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema])
|
| 614 |
+
def test_exclude_in_init(SchemaClass, user):
|
| 615 |
+
s = SchemaClass(exclude=("age", "homepage")).dump(user)
|
| 616 |
+
assert "homepage" not in s
|
| 617 |
+
assert "age" not in s
|
| 618 |
+
assert "name" in s
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema])
|
| 622 |
+
def test_only_in_init(SchemaClass, user):
|
| 623 |
+
s = SchemaClass(only=("name", "age")).dump(user)
|
| 624 |
+
assert "homepage" not in s
|
| 625 |
+
assert "name" in s
|
| 626 |
+
assert "age" in s
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def test_invalid_only_param(user):
|
| 630 |
+
with pytest.raises(ValueError):
|
| 631 |
+
UserSchema(only=("_invalid", "name")).dump(user)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def test_can_serialize_uuid(serialized_user, user):
|
| 635 |
+
assert serialized_user["uid"] == str(user.uid)
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def test_can_serialize_time(user, serialized_user):
|
| 639 |
+
expected = user.time_registered.isoformat()[:15]
|
| 640 |
+
assert serialized_user["time_registered"] == expected
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def test_json_module_is_deprecated():
|
| 644 |
+
with pytest.deprecated_call():
|
| 645 |
+
|
| 646 |
+
class UserJSONSchema(Schema):
|
| 647 |
+
name = fields.String()
|
| 648 |
+
|
| 649 |
+
class Meta:
|
| 650 |
+
json_module = mockjson
|
| 651 |
+
|
| 652 |
+
user = User("Joe")
|
| 653 |
+
s = UserJSONSchema()
|
| 654 |
+
result = s.dumps(user)
|
| 655 |
+
assert result == mockjson.dumps("val")
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def test_render_module():
|
| 659 |
+
class UserJSONSchema(Schema):
|
| 660 |
+
name = fields.String()
|
| 661 |
+
|
| 662 |
+
class Meta:
|
| 663 |
+
render_module = mockjson
|
| 664 |
+
|
| 665 |
+
user = User("Joe")
|
| 666 |
+
s = UserJSONSchema()
|
| 667 |
+
result = s.dumps(user)
|
| 668 |
+
assert result == mockjson.dumps("val")
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def test_custom_error_message():
|
| 672 |
+
class ErrorSchema(Schema):
|
| 673 |
+
email = fields.Email(error_messages={"invalid": "Invalid email"})
|
| 674 |
+
homepage = fields.Url(error_messages={"invalid": "Bad homepage."})
|
| 675 |
+
balance = fields.Decimal(error_messages={"invalid": "Bad balance."})
|
| 676 |
+
|
| 677 |
+
u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"}
|
| 678 |
+
s = ErrorSchema()
|
| 679 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 680 |
+
s.load(u)
|
| 681 |
+
errors = excinfo.value.messages
|
| 682 |
+
assert "Bad balance." in errors["balance"]
|
| 683 |
+
assert "Bad homepage." in errors["homepage"]
|
| 684 |
+
assert "Invalid email" in errors["email"]
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def test_custom_unknown_error_message():
|
| 688 |
+
custom_message = "custom error message."
|
| 689 |
+
|
| 690 |
+
class ErrorSchema(Schema):
|
| 691 |
+
error_messages = {"unknown": custom_message}
|
| 692 |
+
name = fields.String()
|
| 693 |
+
|
| 694 |
+
s = ErrorSchema()
|
| 695 |
+
u = {"name": "Joe", "age": 13}
|
| 696 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 697 |
+
s.load(u)
|
| 698 |
+
errors = excinfo.value.messages
|
| 699 |
+
assert custom_message in errors["age"]
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
def test_custom_type_error_message():
|
| 703 |
+
custom_message = "custom error message."
|
| 704 |
+
|
| 705 |
+
class ErrorSchema(Schema):
|
| 706 |
+
error_messages = {"type": custom_message}
|
| 707 |
+
name = fields.String()
|
| 708 |
+
|
| 709 |
+
s = ErrorSchema()
|
| 710 |
+
u = ["Joe"]
|
| 711 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 712 |
+
s.load(u)
|
| 713 |
+
errors = excinfo.value.messages
|
| 714 |
+
assert custom_message in errors["_schema"]
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
def test_custom_type_error_message_with_many():
|
| 718 |
+
custom_message = "custom error message."
|
| 719 |
+
|
| 720 |
+
class ErrorSchema(Schema):
|
| 721 |
+
error_messages = {"type": custom_message}
|
| 722 |
+
name = fields.String()
|
| 723 |
+
|
| 724 |
+
s = ErrorSchema(many=True)
|
| 725 |
+
u = {"name": "Joe"}
|
| 726 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 727 |
+
s.load(u)
|
| 728 |
+
errors = excinfo.value.messages
|
| 729 |
+
assert custom_message in errors["_schema"]
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def test_custom_error_messages_with_inheritance():
|
| 733 |
+
parent_type_message = "parent type error message."
|
| 734 |
+
parent_unknown_message = "parent unknown error message."
|
| 735 |
+
child_type_message = "child type error message."
|
| 736 |
+
|
| 737 |
+
class ParentSchema(Schema):
|
| 738 |
+
error_messages = {
|
| 739 |
+
"type": parent_type_message,
|
| 740 |
+
"unknown": parent_unknown_message,
|
| 741 |
+
}
|
| 742 |
+
name = fields.String()
|
| 743 |
+
|
| 744 |
+
class ChildSchema(ParentSchema):
|
| 745 |
+
error_messages = {"type": child_type_message}
|
| 746 |
+
|
| 747 |
+
unknown_user = {"name": "Eleven", "age": 12}
|
| 748 |
+
type_user = 11
|
| 749 |
+
|
| 750 |
+
parent_schema = ParentSchema()
|
| 751 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 752 |
+
parent_schema.load(unknown_user)
|
| 753 |
+
assert parent_unknown_message in excinfo.value.messages["age"]
|
| 754 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 755 |
+
parent_schema.load(type_user)
|
| 756 |
+
assert parent_type_message in excinfo.value.messages["_schema"]
|
| 757 |
+
|
| 758 |
+
child_schema = ChildSchema()
|
| 759 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 760 |
+
child_schema.load(unknown_user)
|
| 761 |
+
assert parent_unknown_message in excinfo.value.messages["age"]
|
| 762 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 763 |
+
child_schema.load(type_user)
|
| 764 |
+
assert child_type_message in excinfo.value.messages["_schema"]
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
def test_load_errors_with_many():
|
| 768 |
+
class ErrorSchema(Schema):
|
| 769 |
+
email = fields.Email()
|
| 770 |
+
|
| 771 |
+
data = [
|
| 772 |
+
{"email": "bademail"},
|
| 773 |
+
{"email": "goo@email.com"},
|
| 774 |
+
{"email": "anotherbademail"},
|
| 775 |
+
]
|
| 776 |
+
|
| 777 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 778 |
+
ErrorSchema(many=True).load(data)
|
| 779 |
+
errors = excinfo.value.messages
|
| 780 |
+
assert 0 in errors
|
| 781 |
+
assert 2 in errors
|
| 782 |
+
assert "Not a valid email address." in errors[0]["email"][0]
|
| 783 |
+
assert "Not a valid email address." in errors[2]["email"][0]
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def test_error_raised_if_fields_option_is_not_list():
|
| 787 |
+
with pytest.raises(ValueError):
|
| 788 |
+
|
| 789 |
+
class BadSchema(Schema):
|
| 790 |
+
name = fields.String()
|
| 791 |
+
|
| 792 |
+
class Meta:
|
| 793 |
+
fields = "name"
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
def test_error_raised_if_additional_option_is_not_list():
|
| 797 |
+
with pytest.raises(ValueError):
|
| 798 |
+
|
| 799 |
+
class BadSchema(Schema):
|
| 800 |
+
name = fields.String()
|
| 801 |
+
|
| 802 |
+
class Meta:
|
| 803 |
+
additional = "email"
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
def test_nested_custom_set_in_exclude_reusing_schema():
|
| 807 |
+
class CustomSet:
|
| 808 |
+
# This custom set is to allow the obj check in BaseSchema.__filter_fields
|
| 809 |
+
# to pass, since it'll be a valid instance, and this class overrides
|
| 810 |
+
# getitem method to allow the hasattr check to pass too, which will try
|
| 811 |
+
# to access the first obj index and will simulate a IndexError throwing.
|
| 812 |
+
# e.g. SqlAlchemy.Query is a valid use case for this 'obj'.
|
| 813 |
+
|
| 814 |
+
def __getitem__(self, item):
|
| 815 |
+
return [][item]
|
| 816 |
+
|
| 817 |
+
class ChildSchema(Schema):
|
| 818 |
+
foo = fields.Field(required=True)
|
| 819 |
+
bar = fields.Field()
|
| 820 |
+
|
| 821 |
+
class Meta:
|
| 822 |
+
only = ("bar",)
|
| 823 |
+
|
| 824 |
+
class ParentSchema(Schema):
|
| 825 |
+
child = fields.Nested(ChildSchema, many=True, exclude=("foo",))
|
| 826 |
+
|
| 827 |
+
sch = ParentSchema()
|
| 828 |
+
obj = dict(child=CustomSet())
|
| 829 |
+
sch.dumps(obj)
|
| 830 |
+
data = dict(child=[{"bar": 1}])
|
| 831 |
+
sch.load(data, partial=True)
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
def test_nested_only():
|
| 835 |
+
class ChildSchema(Schema):
|
| 836 |
+
foo = fields.Field()
|
| 837 |
+
bar = fields.Field()
|
| 838 |
+
baz = fields.Field()
|
| 839 |
+
|
| 840 |
+
class ParentSchema(Schema):
|
| 841 |
+
bla = fields.Field()
|
| 842 |
+
bli = fields.Field()
|
| 843 |
+
blubb = fields.Nested(ChildSchema)
|
| 844 |
+
|
| 845 |
+
sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"))
|
| 846 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242))
|
| 847 |
+
result = sch.dump(data)
|
| 848 |
+
assert "bla" in result
|
| 849 |
+
assert "blubb" in result
|
| 850 |
+
assert "bli" not in result
|
| 851 |
+
child = result["blubb"]
|
| 852 |
+
assert "foo" in child
|
| 853 |
+
assert "bar" in child
|
| 854 |
+
assert "baz" not in child
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
def test_nested_only_inheritance():
|
| 858 |
+
class ChildSchema(Schema):
|
| 859 |
+
foo = fields.Field()
|
| 860 |
+
bar = fields.Field()
|
| 861 |
+
baz = fields.Field()
|
| 862 |
+
|
| 863 |
+
class ParentSchema(Schema):
|
| 864 |
+
bla = fields.Field()
|
| 865 |
+
bli = fields.Field()
|
| 866 |
+
blubb = fields.Nested(ChildSchema, only=("foo", "bar"))
|
| 867 |
+
|
| 868 |
+
sch = ParentSchema(only=("blubb.foo", "blubb.baz"))
|
| 869 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242))
|
| 870 |
+
result = sch.dump(data)
|
| 871 |
+
assert "bla" not in result
|
| 872 |
+
assert "blubb" in result
|
| 873 |
+
assert "bli" not in result
|
| 874 |
+
child = result["blubb"]
|
| 875 |
+
assert "foo" in child
|
| 876 |
+
assert "bar" not in child
|
| 877 |
+
assert "baz" not in child
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
def test_nested_only_empty_inheritance():
|
| 881 |
+
class ChildSchema(Schema):
|
| 882 |
+
foo = fields.Field()
|
| 883 |
+
bar = fields.Field()
|
| 884 |
+
baz = fields.Field()
|
| 885 |
+
|
| 886 |
+
class ParentSchema(Schema):
|
| 887 |
+
bla = fields.Field()
|
| 888 |
+
bli = fields.Field()
|
| 889 |
+
blubb = fields.Nested(ChildSchema, only=("bar",))
|
| 890 |
+
|
| 891 |
+
sch = ParentSchema(only=("blubb.foo",))
|
| 892 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242))
|
| 893 |
+
result = sch.dump(data)
|
| 894 |
+
assert "bla" not in result
|
| 895 |
+
assert "blubb" in result
|
| 896 |
+
assert "bli" not in result
|
| 897 |
+
child = result["blubb"]
|
| 898 |
+
assert "foo" not in child
|
| 899 |
+
assert "bar" not in child
|
| 900 |
+
assert "baz" not in child
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
def test_nested_exclude():
|
| 904 |
+
class ChildSchema(Schema):
|
| 905 |
+
foo = fields.Field()
|
| 906 |
+
bar = fields.Field()
|
| 907 |
+
baz = fields.Field()
|
| 908 |
+
|
| 909 |
+
class ParentSchema(Schema):
|
| 910 |
+
bla = fields.Field()
|
| 911 |
+
bli = fields.Field()
|
| 912 |
+
blubb = fields.Nested(ChildSchema)
|
| 913 |
+
|
| 914 |
+
sch = ParentSchema(exclude=("bli", "blubb.baz"))
|
| 915 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242))
|
| 916 |
+
result = sch.dump(data)
|
| 917 |
+
assert "bla" in result
|
| 918 |
+
assert "blubb" in result
|
| 919 |
+
assert "bli" not in result
|
| 920 |
+
child = result["blubb"]
|
| 921 |
+
assert "foo" in child
|
| 922 |
+
assert "bar" in child
|
| 923 |
+
assert "baz" not in child
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
def test_nested_exclude_inheritance():
|
| 927 |
+
class ChildSchema(Schema):
|
| 928 |
+
foo = fields.Field()
|
| 929 |
+
bar = fields.Field()
|
| 930 |
+
baz = fields.Field()
|
| 931 |
+
|
| 932 |
+
class ParentSchema(Schema):
|
| 933 |
+
bla = fields.Field()
|
| 934 |
+
bli = fields.Field()
|
| 935 |
+
blubb = fields.Nested(ChildSchema, exclude=("baz",))
|
| 936 |
+
|
| 937 |
+
sch = ParentSchema(exclude=("blubb.foo",))
|
| 938 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242))
|
| 939 |
+
result = sch.dump(data)
|
| 940 |
+
assert "bla" in result
|
| 941 |
+
assert "blubb" in result
|
| 942 |
+
assert "bli" in result
|
| 943 |
+
child = result["blubb"]
|
| 944 |
+
assert "foo" not in child
|
| 945 |
+
assert "bar" in child
|
| 946 |
+
assert "baz" not in child
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
def test_nested_only_and_exclude():
|
| 950 |
+
class ChildSchema(Schema):
|
| 951 |
+
foo = fields.Field()
|
| 952 |
+
bar = fields.Field()
|
| 953 |
+
baz = fields.Field()
|
| 954 |
+
|
| 955 |
+
class ParentSchema(Schema):
|
| 956 |
+
bla = fields.Field()
|
| 957 |
+
bli = fields.Field()
|
| 958 |
+
blubb = fields.Nested(ChildSchema)
|
| 959 |
+
|
| 960 |
+
sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",))
|
| 961 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242))
|
| 962 |
+
result = sch.dump(data)
|
| 963 |
+
assert "bla" in result
|
| 964 |
+
assert "blubb" in result
|
| 965 |
+
assert "bli" not in result
|
| 966 |
+
child = result["blubb"]
|
| 967 |
+
assert "foo" not in child
|
| 968 |
+
assert "bar" in child
|
| 969 |
+
assert "baz" not in child
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
def test_nested_only_then_exclude_inheritance():
|
| 973 |
+
class ChildSchema(Schema):
|
| 974 |
+
foo = fields.Field()
|
| 975 |
+
bar = fields.Field()
|
| 976 |
+
baz = fields.Field()
|
| 977 |
+
|
| 978 |
+
class ParentSchema(Schema):
|
| 979 |
+
bla = fields.Field()
|
| 980 |
+
bli = fields.Field()
|
| 981 |
+
blubb = fields.Nested(ChildSchema, only=("foo", "bar"))
|
| 982 |
+
|
| 983 |
+
sch = ParentSchema(exclude=("blubb.foo",))
|
| 984 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242))
|
| 985 |
+
result = sch.dump(data)
|
| 986 |
+
assert "bla" in result
|
| 987 |
+
assert "blubb" in result
|
| 988 |
+
assert "bli" in result
|
| 989 |
+
child = result["blubb"]
|
| 990 |
+
assert "foo" not in child
|
| 991 |
+
assert "bar" in child
|
| 992 |
+
assert "baz" not in child
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def test_nested_exclude_then_only_inheritance():
|
| 996 |
+
class ChildSchema(Schema):
|
| 997 |
+
foo = fields.Field()
|
| 998 |
+
bar = fields.Field()
|
| 999 |
+
baz = fields.Field()
|
| 1000 |
+
|
| 1001 |
+
class ParentSchema(Schema):
|
| 1002 |
+
bla = fields.Field()
|
| 1003 |
+
bli = fields.Field()
|
| 1004 |
+
blubb = fields.Nested(ChildSchema, exclude=("foo",))
|
| 1005 |
+
|
| 1006 |
+
sch = ParentSchema(only=("blubb.bar",))
|
| 1007 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242))
|
| 1008 |
+
result = sch.dump(data)
|
| 1009 |
+
assert "bla" not in result
|
| 1010 |
+
assert "blubb" in result
|
| 1011 |
+
assert "bli" not in result
|
| 1012 |
+
child = result["blubb"]
|
| 1013 |
+
assert "foo" not in child
|
| 1014 |
+
assert "bar" in child
|
| 1015 |
+
assert "baz" not in child
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
def test_nested_exclude_and_only_inheritance():
|
| 1019 |
+
class ChildSchema(Schema):
|
| 1020 |
+
foo = fields.Field()
|
| 1021 |
+
bar = fields.Field()
|
| 1022 |
+
baz = fields.Field()
|
| 1023 |
+
ban = fields.Field()
|
| 1024 |
+
fuu = fields.Field()
|
| 1025 |
+
|
| 1026 |
+
class ParentSchema(Schema):
|
| 1027 |
+
bla = fields.Field()
|
| 1028 |
+
bli = fields.Field()
|
| 1029 |
+
blubb = fields.Nested(
|
| 1030 |
+
ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",)
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
sch = ParentSchema(
|
| 1034 |
+
only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",)
|
| 1035 |
+
)
|
| 1036 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242))
|
| 1037 |
+
result = sch.dump(data)
|
| 1038 |
+
assert "bla" not in result
|
| 1039 |
+
assert "blubb" in result
|
| 1040 |
+
assert "bli" not in result
|
| 1041 |
+
child = result["blubb"]
|
| 1042 |
+
assert "foo" not in child
|
| 1043 |
+
assert "bar" in child
|
| 1044 |
+
assert "baz" not in child
|
| 1045 |
+
assert "ban" not in child
|
| 1046 |
+
assert "fuu" not in child
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
# https://github.com/marshmallow-code/marshmallow/issues/1160
|
| 1050 |
+
def test_nested_instance_many():
|
| 1051 |
+
class BookSchema(Schema):
|
| 1052 |
+
id = fields.Int()
|
| 1053 |
+
title = fields.String()
|
| 1054 |
+
|
| 1055 |
+
class UserSchema(Schema):
|
| 1056 |
+
id = fields.Int()
|
| 1057 |
+
name = fields.String()
|
| 1058 |
+
books = fields.Nested(BookSchema(many=True))
|
| 1059 |
+
|
| 1060 |
+
books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}]
|
| 1061 |
+
user = {"id": 1, "name": "Peter", "books": books}
|
| 1062 |
+
|
| 1063 |
+
user_dump = UserSchema().dump(user)
|
| 1064 |
+
assert user_dump["books"] == books
|
| 1065 |
+
|
| 1066 |
+
user_load = UserSchema().load(user_dump)
|
| 1067 |
+
assert user_load == user
|
| 1068 |
+
|
| 1069 |
+
|
| 1070 |
+
def test_nested_instance_only():
|
| 1071 |
+
class ArtistSchema(Schema):
|
| 1072 |
+
first = fields.Str()
|
| 1073 |
+
last = fields.Str()
|
| 1074 |
+
|
| 1075 |
+
class AlbumSchema(Schema):
|
| 1076 |
+
title = fields.Str()
|
| 1077 |
+
artist = fields.Nested(ArtistSchema(), only=("last",))
|
| 1078 |
+
|
| 1079 |
+
schema = AlbumSchema()
|
| 1080 |
+
album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}}
|
| 1081 |
+
loaded = schema.load(album)
|
| 1082 |
+
assert loaded == album
|
| 1083 |
+
full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}}
|
| 1084 |
+
assert schema.dump(full_album) == album
|
| 1085 |
+
|
| 1086 |
+
|
| 1087 |
+
def test_nested_instance_exclude():
|
| 1088 |
+
class ArtistSchema(Schema):
|
| 1089 |
+
first = fields.Str()
|
| 1090 |
+
last = fields.Str()
|
| 1091 |
+
|
| 1092 |
+
class AlbumSchema(Schema):
|
| 1093 |
+
title = fields.Str()
|
| 1094 |
+
artist = fields.Nested(ArtistSchema(), exclude=("first",))
|
| 1095 |
+
|
| 1096 |
+
schema = AlbumSchema()
|
| 1097 |
+
album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}}
|
| 1098 |
+
loaded = schema.load(album)
|
| 1099 |
+
assert loaded == album
|
| 1100 |
+
full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}}
|
| 1101 |
+
assert schema.dump(full_album) == album
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
def test_meta_nested_exclude():
|
| 1105 |
+
class ChildSchema(Schema):
|
| 1106 |
+
foo = fields.Field()
|
| 1107 |
+
bar = fields.Field()
|
| 1108 |
+
baz = fields.Field()
|
| 1109 |
+
|
| 1110 |
+
class ParentSchema(Schema):
|
| 1111 |
+
bla = fields.Field()
|
| 1112 |
+
bli = fields.Field()
|
| 1113 |
+
blubb = fields.Nested(ChildSchema)
|
| 1114 |
+
|
| 1115 |
+
class Meta:
|
| 1116 |
+
exclude = ("blubb.foo",)
|
| 1117 |
+
|
| 1118 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242))
|
| 1119 |
+
|
| 1120 |
+
sch = ParentSchema()
|
| 1121 |
+
result = sch.dump(data)
|
| 1122 |
+
assert "bla" in result
|
| 1123 |
+
assert "blubb" in result
|
| 1124 |
+
assert "bli" in result
|
| 1125 |
+
child = result["blubb"]
|
| 1126 |
+
assert "foo" not in child
|
| 1127 |
+
assert "bar" in child
|
| 1128 |
+
assert "baz" in child
|
| 1129 |
+
|
| 1130 |
+
# Test fields with dot notations in Meta.exclude on multiple instantiations
|
| 1131 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212
|
| 1132 |
+
sch = ParentSchema()
|
| 1133 |
+
result = sch.dump(data)
|
| 1134 |
+
assert "bla" in result
|
| 1135 |
+
assert "blubb" in result
|
| 1136 |
+
assert "bli" in result
|
| 1137 |
+
child = result["blubb"]
|
| 1138 |
+
assert "foo" not in child
|
| 1139 |
+
assert "bar" in child
|
| 1140 |
+
assert "baz" in child
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
def test_nested_custom_set_not_implementing_getitem():
|
| 1144 |
+
# This test checks that marshmallow can serialize implementations of
|
| 1145 |
+
# :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments
|
| 1146 |
+
# that are not integers.
|
| 1147 |
+
|
| 1148 |
+
class ListLikeParent:
|
| 1149 |
+
"""
|
| 1150 |
+
Implements a list-like object that can get children using a
|
| 1151 |
+
non-integer key
|
| 1152 |
+
"""
|
| 1153 |
+
|
| 1154 |
+
def __init__(self, required_key, child):
|
| 1155 |
+
"""
|
| 1156 |
+
:param required_key: The key to use in ``__getitem__`` in order
|
| 1157 |
+
to successfully get the ``child``
|
| 1158 |
+
:param child: The return value of the ``child`` if
|
| 1159 |
+
``__getitem__`` succeeds
|
| 1160 |
+
"""
|
| 1161 |
+
self.children = {required_key: child}
|
| 1162 |
+
|
| 1163 |
+
class Child:
|
| 1164 |
+
"""
|
| 1165 |
+
Implements an object with some attribute
|
| 1166 |
+
"""
|
| 1167 |
+
|
| 1168 |
+
def __init__(self, attribute):
|
| 1169 |
+
"""
|
| 1170 |
+
:param str attribute: The attribute to initialize
|
| 1171 |
+
"""
|
| 1172 |
+
self.attribute = attribute
|
| 1173 |
+
|
| 1174 |
+
class ChildSchema(Schema):
|
| 1175 |
+
"""
|
| 1176 |
+
The marshmallow schema for the child
|
| 1177 |
+
"""
|
| 1178 |
+
|
| 1179 |
+
attribute = fields.Str()
|
| 1180 |
+
|
| 1181 |
+
class ParentSchema(Schema):
|
| 1182 |
+
"""
|
| 1183 |
+
The schema for the parent
|
| 1184 |
+
"""
|
| 1185 |
+
|
| 1186 |
+
children = fields.Nested(ChildSchema, many=True)
|
| 1187 |
+
|
| 1188 |
+
attribute = "Foo"
|
| 1189 |
+
required_key = "key"
|
| 1190 |
+
child = Child(attribute)
|
| 1191 |
+
|
| 1192 |
+
parent = ListLikeParent(required_key, child)
|
| 1193 |
+
|
| 1194 |
+
ParentSchema().dump(parent)
|
| 1195 |
+
|
| 1196 |
+
|
| 1197 |
+
def test_deeply_nested_only_and_exclude():
|
| 1198 |
+
class GrandChildSchema(Schema):
|
| 1199 |
+
goo = fields.Field()
|
| 1200 |
+
gah = fields.Field()
|
| 1201 |
+
bah = fields.Field()
|
| 1202 |
+
|
| 1203 |
+
class ChildSchema(Schema):
|
| 1204 |
+
foo = fields.Field()
|
| 1205 |
+
bar = fields.Field()
|
| 1206 |
+
flubb = fields.Nested(GrandChildSchema)
|
| 1207 |
+
|
| 1208 |
+
class ParentSchema(Schema):
|
| 1209 |
+
bla = fields.Field()
|
| 1210 |
+
bli = fields.Field()
|
| 1211 |
+
blubb = fields.Nested(ChildSchema)
|
| 1212 |
+
|
| 1213 |
+
sch = ParentSchema(
|
| 1214 |
+
only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"),
|
| 1215 |
+
exclude=("blubb.flubb.goo",),
|
| 1216 |
+
)
|
| 1217 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7)))
|
| 1218 |
+
result = sch.dump(data)
|
| 1219 |
+
assert "bla" in result
|
| 1220 |
+
assert "blubb" in result
|
| 1221 |
+
assert "bli" not in result
|
| 1222 |
+
child = result["blubb"]
|
| 1223 |
+
assert "foo" in child
|
| 1224 |
+
assert "flubb" in child
|
| 1225 |
+
assert "bar" not in child
|
| 1226 |
+
grand_child = child["flubb"]
|
| 1227 |
+
assert "gah" in grand_child
|
| 1228 |
+
assert "goo" not in grand_child
|
| 1229 |
+
assert "bah" not in grand_child
|
| 1230 |
+
|
| 1231 |
+
|
| 1232 |
+
def test_nested_lambda():
|
| 1233 |
+
class ChildSchema(Schema):
|
| 1234 |
+
id = fields.Str()
|
| 1235 |
+
name = fields.Str()
|
| 1236 |
+
parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True)
|
| 1237 |
+
siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name"))))
|
| 1238 |
+
|
| 1239 |
+
class ParentSchema(Schema):
|
| 1240 |
+
id = fields.Str()
|
| 1241 |
+
spouse = fields.Nested(lambda: ParentSchema(only=("id",)))
|
| 1242 |
+
children = fields.List(
|
| 1243 |
+
fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings")))
|
| 1244 |
+
)
|
| 1245 |
+
|
| 1246 |
+
sch = ParentSchema()
|
| 1247 |
+
data_to_load = {
|
| 1248 |
+
"id": "p1",
|
| 1249 |
+
"spouse": {"id": "p2"},
|
| 1250 |
+
"children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}],
|
| 1251 |
+
}
|
| 1252 |
+
loaded = sch.load(data_to_load)
|
| 1253 |
+
assert loaded == data_to_load
|
| 1254 |
+
|
| 1255 |
+
data_to_dump = dict(
|
| 1256 |
+
id="p2",
|
| 1257 |
+
spouse=dict(id="p2"),
|
| 1258 |
+
children=[
|
| 1259 |
+
dict(
|
| 1260 |
+
id="c1",
|
| 1261 |
+
name="bar",
|
| 1262 |
+
parent=dict(id="p2"),
|
| 1263 |
+
siblings=[dict(id="c2", name="sis")],
|
| 1264 |
+
)
|
| 1265 |
+
],
|
| 1266 |
+
)
|
| 1267 |
+
dumped = sch.dump(data_to_dump)
|
| 1268 |
+
assert dumped == {
|
| 1269 |
+
"id": "p2",
|
| 1270 |
+
"spouse": {"id": "p2"},
|
| 1271 |
+
"children": [
|
| 1272 |
+
{
|
| 1273 |
+
"id": "c1",
|
| 1274 |
+
"parent": {"id": "p2"},
|
| 1275 |
+
"siblings": [{"id": "c2", "name": "sis"}],
|
| 1276 |
+
}
|
| 1277 |
+
],
|
| 1278 |
+
}
|
| 1279 |
+
|
| 1280 |
+
|
| 1281 |
+
@pytest.mark.parametrize("data_key", ("f1", "f5", None))
|
| 1282 |
+
def test_data_key_collision(data_key):
|
| 1283 |
+
class MySchema(Schema):
|
| 1284 |
+
f1 = fields.Field()
|
| 1285 |
+
f2 = fields.Field(data_key=data_key)
|
| 1286 |
+
f3 = fields.Field(data_key="f5")
|
| 1287 |
+
f4 = fields.Field(data_key="f1", load_only=True)
|
| 1288 |
+
|
| 1289 |
+
if data_key is None:
|
| 1290 |
+
MySchema()
|
| 1291 |
+
else:
|
| 1292 |
+
with pytest.raises(ValueError, match=data_key):
|
| 1293 |
+
MySchema()
|
| 1294 |
+
|
| 1295 |
+
|
| 1296 |
+
@pytest.mark.parametrize("attribute", ("f1", "f5", None))
|
| 1297 |
+
def test_attribute_collision(attribute):
|
| 1298 |
+
class MySchema(Schema):
|
| 1299 |
+
f1 = fields.Field()
|
| 1300 |
+
f2 = fields.Field(attribute=attribute)
|
| 1301 |
+
f3 = fields.Field(attribute="f5")
|
| 1302 |
+
f4 = fields.Field(attribute="f1", dump_only=True)
|
| 1303 |
+
|
| 1304 |
+
if attribute is None:
|
| 1305 |
+
MySchema()
|
| 1306 |
+
else:
|
| 1307 |
+
with pytest.raises(ValueError, match=attribute):
|
| 1308 |
+
MySchema()
|
| 1309 |
+
|
| 1310 |
+
|
| 1311 |
+
class TestDeeplyNestedLoadOnly:
|
| 1312 |
+
@pytest.fixture()
|
| 1313 |
+
def schema(self):
|
| 1314 |
+
class GrandChildSchema(Schema):
|
| 1315 |
+
str_dump_only = fields.String()
|
| 1316 |
+
str_load_only = fields.String()
|
| 1317 |
+
str_regular = fields.String()
|
| 1318 |
+
|
| 1319 |
+
class ChildSchema(Schema):
|
| 1320 |
+
str_dump_only = fields.String()
|
| 1321 |
+
str_load_only = fields.String()
|
| 1322 |
+
str_regular = fields.String()
|
| 1323 |
+
grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE)
|
| 1324 |
+
|
| 1325 |
+
class ParentSchema(Schema):
|
| 1326 |
+
str_dump_only = fields.String()
|
| 1327 |
+
str_load_only = fields.String()
|
| 1328 |
+
str_regular = fields.String()
|
| 1329 |
+
child = fields.Nested(ChildSchema, unknown=EXCLUDE)
|
| 1330 |
+
|
| 1331 |
+
return ParentSchema(
|
| 1332 |
+
dump_only=(
|
| 1333 |
+
"str_dump_only",
|
| 1334 |
+
"child.str_dump_only",
|
| 1335 |
+
"child.grand_child.str_dump_only",
|
| 1336 |
+
),
|
| 1337 |
+
load_only=(
|
| 1338 |
+
"str_load_only",
|
| 1339 |
+
"child.str_load_only",
|
| 1340 |
+
"child.grand_child.str_load_only",
|
| 1341 |
+
),
|
| 1342 |
+
)
|
| 1343 |
+
|
| 1344 |
+
@pytest.fixture()
|
| 1345 |
+
def data(self):
|
| 1346 |
+
return dict(
|
| 1347 |
+
str_dump_only="Dump Only",
|
| 1348 |
+
str_load_only="Load Only",
|
| 1349 |
+
str_regular="Regular String",
|
| 1350 |
+
child=dict(
|
| 1351 |
+
str_dump_only="Dump Only",
|
| 1352 |
+
str_load_only="Load Only",
|
| 1353 |
+
str_regular="Regular String",
|
| 1354 |
+
grand_child=dict(
|
| 1355 |
+
str_dump_only="Dump Only",
|
| 1356 |
+
str_load_only="Load Only",
|
| 1357 |
+
str_regular="Regular String",
|
| 1358 |
+
),
|
| 1359 |
+
),
|
| 1360 |
+
)
|
| 1361 |
+
|
| 1362 |
+
def test_load_only(self, schema, data):
|
| 1363 |
+
result = schema.dump(data)
|
| 1364 |
+
assert "str_load_only" not in result
|
| 1365 |
+
assert "str_dump_only" in result
|
| 1366 |
+
assert "str_regular" in result
|
| 1367 |
+
child = result["child"]
|
| 1368 |
+
assert "str_load_only" not in child
|
| 1369 |
+
assert "str_dump_only" in child
|
| 1370 |
+
assert "str_regular" in child
|
| 1371 |
+
grand_child = child["grand_child"]
|
| 1372 |
+
assert "str_load_only" not in grand_child
|
| 1373 |
+
assert "str_dump_only" in grand_child
|
| 1374 |
+
assert "str_regular" in grand_child
|
| 1375 |
+
|
| 1376 |
+
def test_dump_only(self, schema, data):
|
| 1377 |
+
result = schema.load(data, unknown=EXCLUDE)
|
| 1378 |
+
assert "str_dump_only" not in result
|
| 1379 |
+
assert "str_load_only" in result
|
| 1380 |
+
assert "str_regular" in result
|
| 1381 |
+
child = result["child"]
|
| 1382 |
+
assert "str_dump_only" not in child
|
| 1383 |
+
assert "str_load_only" in child
|
| 1384 |
+
assert "str_regular" in child
|
| 1385 |
+
grand_child = child["grand_child"]
|
| 1386 |
+
assert "str_dump_only" not in grand_child
|
| 1387 |
+
assert "str_load_only" in grand_child
|
| 1388 |
+
assert "str_regular" in grand_child
|
| 1389 |
+
|
| 1390 |
+
|
| 1391 |
+
class TestDeeplyNestedListLoadOnly:
|
| 1392 |
+
@pytest.fixture()
|
| 1393 |
+
def schema(self):
|
| 1394 |
+
class ChildSchema(Schema):
|
| 1395 |
+
str_dump_only = fields.String()
|
| 1396 |
+
str_load_only = fields.String()
|
| 1397 |
+
str_regular = fields.String()
|
| 1398 |
+
|
| 1399 |
+
class ParentSchema(Schema):
|
| 1400 |
+
str_dump_only = fields.String()
|
| 1401 |
+
str_load_only = fields.String()
|
| 1402 |
+
str_regular = fields.String()
|
| 1403 |
+
child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE))
|
| 1404 |
+
|
| 1405 |
+
return ParentSchema(
|
| 1406 |
+
dump_only=("str_dump_only", "child.str_dump_only"),
|
| 1407 |
+
load_only=("str_load_only", "child.str_load_only"),
|
| 1408 |
+
)
|
| 1409 |
+
|
| 1410 |
+
@pytest.fixture()
|
| 1411 |
+
def data(self):
|
| 1412 |
+
return dict(
|
| 1413 |
+
str_dump_only="Dump Only",
|
| 1414 |
+
str_load_only="Load Only",
|
| 1415 |
+
str_regular="Regular String",
|
| 1416 |
+
child=[
|
| 1417 |
+
dict(
|
| 1418 |
+
str_dump_only="Dump Only",
|
| 1419 |
+
str_load_only="Load Only",
|
| 1420 |
+
str_regular="Regular String",
|
| 1421 |
+
)
|
| 1422 |
+
],
|
| 1423 |
+
)
|
| 1424 |
+
|
| 1425 |
+
def test_load_only(self, schema, data):
|
| 1426 |
+
result = schema.dump(data)
|
| 1427 |
+
assert "str_load_only" not in result
|
| 1428 |
+
assert "str_dump_only" in result
|
| 1429 |
+
assert "str_regular" in result
|
| 1430 |
+
child = result["child"][0]
|
| 1431 |
+
assert "str_load_only" not in child
|
| 1432 |
+
assert "str_dump_only" in child
|
| 1433 |
+
assert "str_regular" in child
|
| 1434 |
+
|
| 1435 |
+
def test_dump_only(self, schema, data):
|
| 1436 |
+
result = schema.load(data, unknown=EXCLUDE)
|
| 1437 |
+
assert "str_dump_only" not in result
|
| 1438 |
+
assert "str_load_only" in result
|
| 1439 |
+
assert "str_regular" in result
|
| 1440 |
+
child = result["child"][0]
|
| 1441 |
+
assert "str_dump_only" not in child
|
| 1442 |
+
assert "str_load_only" in child
|
| 1443 |
+
assert "str_regular" in child
|
| 1444 |
+
|
| 1445 |
+
|
| 1446 |
+
def test_nested_constructor_only_and_exclude():
|
| 1447 |
+
class GrandChildSchema(Schema):
|
| 1448 |
+
goo = fields.Field()
|
| 1449 |
+
gah = fields.Field()
|
| 1450 |
+
bah = fields.Field()
|
| 1451 |
+
|
| 1452 |
+
class ChildSchema(Schema):
|
| 1453 |
+
foo = fields.Field()
|
| 1454 |
+
bar = fields.Field()
|
| 1455 |
+
flubb = fields.Nested(GrandChildSchema)
|
| 1456 |
+
|
| 1457 |
+
class ParentSchema(Schema):
|
| 1458 |
+
bla = fields.Field()
|
| 1459 |
+
bli = fields.Field()
|
| 1460 |
+
blubb = fields.Nested(
|
| 1461 |
+
ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",)
|
| 1462 |
+
)
|
| 1463 |
+
|
| 1464 |
+
sch = ParentSchema(only=("bla", "blubb"))
|
| 1465 |
+
data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7)))
|
| 1466 |
+
result = sch.dump(data)
|
| 1467 |
+
assert "bla" in result
|
| 1468 |
+
assert "blubb" in result
|
| 1469 |
+
assert "bli" not in result
|
| 1470 |
+
child = result["blubb"]
|
| 1471 |
+
assert "foo" in child
|
| 1472 |
+
assert "flubb" in child
|
| 1473 |
+
assert "bar" not in child
|
| 1474 |
+
grand_child = child["flubb"]
|
| 1475 |
+
assert "gah" in grand_child
|
| 1476 |
+
assert "goo" not in grand_child
|
| 1477 |
+
assert "bah" not in grand_child
|
| 1478 |
+
|
| 1479 |
+
|
| 1480 |
+
def test_only_and_exclude():
|
| 1481 |
+
class MySchema(Schema):
|
| 1482 |
+
foo = fields.Field()
|
| 1483 |
+
bar = fields.Field()
|
| 1484 |
+
baz = fields.Field()
|
| 1485 |
+
|
| 1486 |
+
sch = MySchema(only=("foo", "bar"), exclude=("bar",))
|
| 1487 |
+
data = dict(foo=42, bar=24, baz=242)
|
| 1488 |
+
result = sch.dump(data)
|
| 1489 |
+
assert "foo" in result
|
| 1490 |
+
assert "bar" not in result
|
| 1491 |
+
|
| 1492 |
+
|
| 1493 |
+
def test_only_and_exclude_with_fields():
|
| 1494 |
+
class MySchema(Schema):
|
| 1495 |
+
foo = fields.Field()
|
| 1496 |
+
|
| 1497 |
+
class Meta:
|
| 1498 |
+
fields = ("bar", "baz")
|
| 1499 |
+
|
| 1500 |
+
sch = MySchema(only=("bar", "baz"), exclude=("bar",))
|
| 1501 |
+
data = dict(foo=42, bar=24, baz=242)
|
| 1502 |
+
result = sch.dump(data)
|
| 1503 |
+
assert "baz" in result
|
| 1504 |
+
assert "bar" not in result
|
| 1505 |
+
|
| 1506 |
+
|
| 1507 |
+
def test_invalid_only_and_exclude_with_fields():
|
| 1508 |
+
class MySchema(Schema):
|
| 1509 |
+
foo = fields.Field()
|
| 1510 |
+
|
| 1511 |
+
class Meta:
|
| 1512 |
+
fields = ("bar", "baz")
|
| 1513 |
+
|
| 1514 |
+
with pytest.raises(ValueError) as excinfo:
|
| 1515 |
+
MySchema(only=("foo", "par"), exclude=("ban",))
|
| 1516 |
+
|
| 1517 |
+
assert "foo" in str(excinfo.value)
|
| 1518 |
+
assert "par" in str(excinfo.value)
|
| 1519 |
+
assert "ban" in str(excinfo.value)
|
| 1520 |
+
|
| 1521 |
+
|
| 1522 |
+
def test_only_and_exclude_with_additional():
|
| 1523 |
+
class MySchema(Schema):
|
| 1524 |
+
foo = fields.Field()
|
| 1525 |
+
|
| 1526 |
+
class Meta:
|
| 1527 |
+
additional = ("bar", "baz")
|
| 1528 |
+
|
| 1529 |
+
sch = MySchema(only=("foo", "bar"), exclude=("bar",))
|
| 1530 |
+
data = dict(foo=42, bar=24, baz=242)
|
| 1531 |
+
result = sch.dump(data)
|
| 1532 |
+
assert "foo" in result
|
| 1533 |
+
assert "bar" not in result
|
| 1534 |
+
|
| 1535 |
+
|
| 1536 |
+
def test_invalid_only_and_exclude_with_additional():
|
| 1537 |
+
class MySchema(Schema):
|
| 1538 |
+
foo = fields.Field()
|
| 1539 |
+
|
| 1540 |
+
class Meta:
|
| 1541 |
+
additional = ("bar", "baz")
|
| 1542 |
+
|
| 1543 |
+
with pytest.raises(ValueError) as excinfo:
|
| 1544 |
+
MySchema(only=("foop", "par"), exclude=("ban",))
|
| 1545 |
+
|
| 1546 |
+
assert "foop" in str(excinfo.value)
|
| 1547 |
+
assert "par" in str(excinfo.value)
|
| 1548 |
+
assert "ban" in str(excinfo.value)
|
| 1549 |
+
|
| 1550 |
+
|
| 1551 |
+
def test_exclude_invalid_attribute():
|
| 1552 |
+
class MySchema(Schema):
|
| 1553 |
+
foo = fields.Field()
|
| 1554 |
+
|
| 1555 |
+
with pytest.raises(ValueError, match="'bar'"):
|
| 1556 |
+
MySchema(exclude=("bar",))
|
| 1557 |
+
|
| 1558 |
+
|
| 1559 |
+
def test_only_bounded_by_fields():
|
| 1560 |
+
class MySchema(Schema):
|
| 1561 |
+
class Meta:
|
| 1562 |
+
fields = ("foo",)
|
| 1563 |
+
|
| 1564 |
+
with pytest.raises(ValueError, match="'baz'"):
|
| 1565 |
+
MySchema(only=("baz",))
|
| 1566 |
+
|
| 1567 |
+
|
| 1568 |
+
def test_only_bounded_by_additional():
|
| 1569 |
+
class MySchema(Schema):
|
| 1570 |
+
class Meta:
|
| 1571 |
+
additional = ("b",)
|
| 1572 |
+
|
| 1573 |
+
with pytest.raises(ValueError):
|
| 1574 |
+
MySchema(only=("c",)).dump({"c": 3})
|
| 1575 |
+
|
| 1576 |
+
|
| 1577 |
+
def test_only_empty():
|
| 1578 |
+
class MySchema(Schema):
|
| 1579 |
+
foo = fields.Field()
|
| 1580 |
+
|
| 1581 |
+
sch = MySchema(only=())
|
| 1582 |
+
assert "foo" not in sch.dump({"foo": "bar"})
|
| 1583 |
+
|
| 1584 |
+
|
| 1585 |
+
@pytest.mark.parametrize("param", ("only", "exclude"))
|
| 1586 |
+
def test_only_and_exclude_as_string(param):
|
| 1587 |
+
class MySchema(Schema):
|
| 1588 |
+
foo = fields.Field()
|
| 1589 |
+
|
| 1590 |
+
with pytest.raises(StringNotCollectionError):
|
| 1591 |
+
MySchema(**{param: "foo"})
|
| 1592 |
+
|
| 1593 |
+
|
| 1594 |
+
def test_nested_with_sets():
|
| 1595 |
+
class Inner(Schema):
|
| 1596 |
+
foo = fields.Field()
|
| 1597 |
+
|
| 1598 |
+
class Outer(Schema):
|
| 1599 |
+
inners = fields.Nested(Inner, many=True)
|
| 1600 |
+
|
| 1601 |
+
sch = Outer()
|
| 1602 |
+
|
| 1603 |
+
DataClass = namedtuple("DataClass", ["foo"])
|
| 1604 |
+
data = dict(inners={DataClass(42), DataClass(2)})
|
| 1605 |
+
result = sch.dump(data)
|
| 1606 |
+
assert len(result["inners"]) == 2
|
| 1607 |
+
|
| 1608 |
+
|
| 1609 |
+
def test_meta_serializer_fields():
|
| 1610 |
+
u = User("John", age=42.3, email="john@example.com", homepage="http://john.com")
|
| 1611 |
+
result = UserMetaSchema().dump(u)
|
| 1612 |
+
assert result["name"] == u.name
|
| 1613 |
+
assert result["balance"] == decimal.Decimal("100.00")
|
| 1614 |
+
assert result["uppername"] == "JOHN"
|
| 1615 |
+
assert result["is_old"] is False
|
| 1616 |
+
assert result["created"] == utils.isoformat(u.created)
|
| 1617 |
+
assert result["finger_count"] == 10
|
| 1618 |
+
assert result["various_data"] == dict(u.various_data)
|
| 1619 |
+
|
| 1620 |
+
|
| 1621 |
+
def test_meta_fields_mapping(user):
|
| 1622 |
+
s = UserMetaSchema()
|
| 1623 |
+
s.dump(user) # need to call dump to update fields
|
| 1624 |
+
assert type(s.fields["balance"]) is fields.Decimal
|
| 1625 |
+
# Inferred fields
|
| 1626 |
+
assert type(s.fields["name"]._field_cache[fields.String]) is fields.String
|
| 1627 |
+
assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime
|
| 1628 |
+
assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime
|
| 1629 |
+
assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float
|
| 1630 |
+
assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean
|
| 1631 |
+
assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw
|
| 1632 |
+
assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw
|
| 1633 |
+
assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer
|
| 1634 |
+
assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID
|
| 1635 |
+
assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time
|
| 1636 |
+
assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date
|
| 1637 |
+
assert (
|
| 1638 |
+
type(s.fields["since_created"]._field_cache[fields.TimeDelta])
|
| 1639 |
+
is fields.TimeDelta
|
| 1640 |
+
)
|
| 1641 |
+
|
| 1642 |
+
|
| 1643 |
+
def test_meta_field_not_on_obj_raises_attribute_error(user):
|
| 1644 |
+
class BadUserSchema(Schema):
|
| 1645 |
+
class Meta:
|
| 1646 |
+
fields = ("name",)
|
| 1647 |
+
exclude = ("notfound",)
|
| 1648 |
+
|
| 1649 |
+
with pytest.raises(ValueError, match="'notfound'"):
|
| 1650 |
+
BadUserSchema().dump(user)
|
| 1651 |
+
|
| 1652 |
+
|
| 1653 |
+
def test_exclude_fields(user):
|
| 1654 |
+
s = UserExcludeSchema().dump(user)
|
| 1655 |
+
assert "created" not in s
|
| 1656 |
+
assert "updated" not in s
|
| 1657 |
+
assert "name" in s
|
| 1658 |
+
|
| 1659 |
+
|
| 1660 |
+
def test_fields_option_must_be_list_or_tuple():
|
| 1661 |
+
with pytest.raises(ValueError):
|
| 1662 |
+
|
| 1663 |
+
class BadFields(Schema):
|
| 1664 |
+
class Meta:
|
| 1665 |
+
fields = "name"
|
| 1666 |
+
|
| 1667 |
+
|
| 1668 |
+
def test_exclude_option_must_be_list_or_tuple():
|
| 1669 |
+
with pytest.raises(ValueError):
|
| 1670 |
+
|
| 1671 |
+
class BadExclude(Schema):
|
| 1672 |
+
class Meta:
|
| 1673 |
+
exclude = "name"
|
| 1674 |
+
|
| 1675 |
+
|
| 1676 |
+
def test_datetimeformat_option(user):
|
| 1677 |
+
meta_fmt = "%Y-%m"
|
| 1678 |
+
field_fmt = "%m-%d"
|
| 1679 |
+
|
| 1680 |
+
class DateTimeFormatSchema(Schema):
|
| 1681 |
+
updated = fields.DateTime(field_fmt)
|
| 1682 |
+
|
| 1683 |
+
class Meta:
|
| 1684 |
+
fields = ("created", "updated")
|
| 1685 |
+
datetimeformat = meta_fmt
|
| 1686 |
+
|
| 1687 |
+
serialized = DateTimeFormatSchema().dump(user)
|
| 1688 |
+
assert serialized["created"] == user.created.strftime(meta_fmt)
|
| 1689 |
+
assert serialized["updated"] == user.updated.strftime(field_fmt)
|
| 1690 |
+
|
| 1691 |
+
|
| 1692 |
+
def test_dateformat_option(user):
|
| 1693 |
+
fmt = "%Y-%m"
|
| 1694 |
+
field_fmt = "%m-%d"
|
| 1695 |
+
|
| 1696 |
+
class DateFormatSchema(Schema):
|
| 1697 |
+
birthdate = fields.Date(field_fmt)
|
| 1698 |
+
|
| 1699 |
+
class Meta:
|
| 1700 |
+
fields = ("birthdate", "activation_date")
|
| 1701 |
+
dateformat = fmt
|
| 1702 |
+
|
| 1703 |
+
serialized = DateFormatSchema().dump(user)
|
| 1704 |
+
assert serialized["birthdate"] == user.birthdate.strftime(field_fmt)
|
| 1705 |
+
assert serialized["activation_date"] == user.activation_date.strftime(fmt)
|
| 1706 |
+
|
| 1707 |
+
|
| 1708 |
+
def test_timeformat_option(user):
|
| 1709 |
+
fmt = "%H:%M:%S"
|
| 1710 |
+
field_fmt = "%H:%M"
|
| 1711 |
+
|
| 1712 |
+
class TimeFormatSchema(Schema):
|
| 1713 |
+
birthtime = fields.Time(field_fmt)
|
| 1714 |
+
|
| 1715 |
+
class Meta:
|
| 1716 |
+
fields = ("birthtime", "time_registered")
|
| 1717 |
+
timeformat = fmt
|
| 1718 |
+
|
| 1719 |
+
serialized = TimeFormatSchema().dump(user)
|
| 1720 |
+
assert serialized["birthtime"] == user.birthtime.strftime(field_fmt)
|
| 1721 |
+
assert serialized["time_registered"] == user.time_registered.strftime(fmt)
|
| 1722 |
+
|
| 1723 |
+
|
| 1724 |
+
def test_default_dateformat(user):
|
| 1725 |
+
class DateFormatSchema(Schema):
|
| 1726 |
+
updated = fields.DateTime(format="%m-%d")
|
| 1727 |
+
|
| 1728 |
+
class Meta:
|
| 1729 |
+
fields = ("created", "updated")
|
| 1730 |
+
|
| 1731 |
+
serialized = DateFormatSchema().dump(user)
|
| 1732 |
+
assert serialized["created"] == utils.isoformat(user.created)
|
| 1733 |
+
assert serialized["updated"] == user.updated.strftime("%m-%d")
|
| 1734 |
+
|
| 1735 |
+
|
| 1736 |
+
def test_inherit_meta(user):
|
| 1737 |
+
class InheritedMetaSchema(UserMetaSchema):
|
| 1738 |
+
pass
|
| 1739 |
+
|
| 1740 |
+
result = InheritedMetaSchema().dump(user)
|
| 1741 |
+
expected = UserMetaSchema().dump(user)
|
| 1742 |
+
assert result == expected
|
| 1743 |
+
|
| 1744 |
+
|
| 1745 |
+
def test_inherit_meta_override():
|
| 1746 |
+
class Parent(Schema):
|
| 1747 |
+
class Meta:
|
| 1748 |
+
fields = ("name", "email")
|
| 1749 |
+
dump_only = ("name",)
|
| 1750 |
+
|
| 1751 |
+
class Child(Schema):
|
| 1752 |
+
class Meta(Parent.Meta):
|
| 1753 |
+
dump_only = ("name", "email")
|
| 1754 |
+
|
| 1755 |
+
child = Child()
|
| 1756 |
+
assert child.opts.fields == ("name", "email")
|
| 1757 |
+
assert child.opts.dump_only == ("name", "email")
|
| 1758 |
+
|
| 1759 |
+
|
| 1760 |
+
def test_additional(user):
|
| 1761 |
+
s = UserAdditionalSchema().dump(user)
|
| 1762 |
+
assert s["lowername"] == user.name.lower()
|
| 1763 |
+
assert s["name"] == user.name
|
| 1764 |
+
|
| 1765 |
+
|
| 1766 |
+
def test_cant_set_both_additional_and_fields(user):
|
| 1767 |
+
with pytest.raises(ValueError):
|
| 1768 |
+
|
| 1769 |
+
class BadSchema(Schema):
|
| 1770 |
+
name = fields.String()
|
| 1771 |
+
|
| 1772 |
+
class Meta:
|
| 1773 |
+
fields = ("name", "email")
|
| 1774 |
+
additional = ("email", "homepage")
|
| 1775 |
+
|
| 1776 |
+
|
| 1777 |
+
def test_serializing_none_meta():
|
| 1778 |
+
s = UserMetaSchema().dump(None)
|
| 1779 |
+
assert s == {}
|
| 1780 |
+
|
| 1781 |
+
|
| 1782 |
+
class CustomError(Exception):
|
| 1783 |
+
pass
|
| 1784 |
+
|
| 1785 |
+
|
| 1786 |
+
class MySchema(Schema):
|
| 1787 |
+
name = fields.String()
|
| 1788 |
+
email = fields.Email()
|
| 1789 |
+
age = fields.Integer()
|
| 1790 |
+
|
| 1791 |
+
def handle_error(self, errors, obj, **kwargs):
|
| 1792 |
+
raise CustomError("Something bad happened")
|
| 1793 |
+
|
| 1794 |
+
def test_load_with_custom_error_handler(self):
|
| 1795 |
+
in_data = {"email": "invalid"}
|
| 1796 |
+
|
| 1797 |
+
class MySchema3(Schema):
|
| 1798 |
+
email = fields.Email()
|
| 1799 |
+
|
| 1800 |
+
def handle_error(self, error, data, **kwargs):
|
| 1801 |
+
assert type(error) is ValidationError
|
| 1802 |
+
assert "email" in error.messages
|
| 1803 |
+
assert list(error.messages.keys()) == ["email"]
|
| 1804 |
+
assert data == in_data
|
| 1805 |
+
raise CustomError("Something bad happened")
|
| 1806 |
+
|
| 1807 |
+
with pytest.raises(CustomError):
|
| 1808 |
+
MySchema3().load(in_data)
|
| 1809 |
+
|
| 1810 |
+
def test_load_with_custom_error_handler_and_partially_valid_data(self):
|
| 1811 |
+
in_data = {"email": "invalid", "url": "http://valid.com"}
|
| 1812 |
+
|
| 1813 |
+
class MySchema(Schema):
|
| 1814 |
+
email = fields.Email()
|
| 1815 |
+
url = fields.URL()
|
| 1816 |
+
|
| 1817 |
+
def handle_error(self, error, data, **kwargs):
|
| 1818 |
+
assert type(error) is ValidationError
|
| 1819 |
+
assert "email" in error.messages
|
| 1820 |
+
assert list(error.messages.keys()) == ["email"]
|
| 1821 |
+
assert data == in_data
|
| 1822 |
+
raise CustomError("Something bad happened")
|
| 1823 |
+
|
| 1824 |
+
with pytest.raises(CustomError):
|
| 1825 |
+
MySchema().load(in_data)
|
| 1826 |
+
|
| 1827 |
+
def test_custom_error_handler_with_validates_decorator(self):
|
| 1828 |
+
in_data = {"num": -1}
|
| 1829 |
+
|
| 1830 |
+
class MySchema(Schema):
|
| 1831 |
+
num = fields.Int()
|
| 1832 |
+
|
| 1833 |
+
@validates("num")
|
| 1834 |
+
def validate_num(self, value):
|
| 1835 |
+
if value < 0:
|
| 1836 |
+
raise ValidationError("Must be greater than 0.")
|
| 1837 |
+
|
| 1838 |
+
def handle_error(self, error, data, **kwargs):
|
| 1839 |
+
assert type(error) is ValidationError
|
| 1840 |
+
assert "num" in error.messages
|
| 1841 |
+
assert list(error.messages.keys()) == ["num"]
|
| 1842 |
+
assert data == in_data
|
| 1843 |
+
raise CustomError("Something bad happened")
|
| 1844 |
+
|
| 1845 |
+
with pytest.raises(CustomError):
|
| 1846 |
+
MySchema().load(in_data)
|
| 1847 |
+
|
| 1848 |
+
def test_custom_error_handler_with_validates_schema_decorator(self):
|
| 1849 |
+
in_data = {"num": -1}
|
| 1850 |
+
|
| 1851 |
+
class MySchema(Schema):
|
| 1852 |
+
num = fields.Int()
|
| 1853 |
+
|
| 1854 |
+
@validates_schema
|
| 1855 |
+
def validates_schema(self, data, **kwargs):
|
| 1856 |
+
raise ValidationError("Invalid schema!")
|
| 1857 |
+
|
| 1858 |
+
def handle_error(self, error, data, **kwargs):
|
| 1859 |
+
assert type(error) is ValidationError
|
| 1860 |
+
assert list(error.messages.keys()) == ["_schema"]
|
| 1861 |
+
assert data == in_data
|
| 1862 |
+
raise CustomError("Something bad happened")
|
| 1863 |
+
|
| 1864 |
+
with pytest.raises(CustomError):
|
| 1865 |
+
MySchema().load(in_data)
|
| 1866 |
+
|
| 1867 |
+
def test_validate_with_custom_error_handler(self):
|
| 1868 |
+
with pytest.raises(CustomError):
|
| 1869 |
+
MySchema().validate({"age": "notvalid", "email": "invalid"})
|
| 1870 |
+
|
| 1871 |
+
|
| 1872 |
+
class TestFieldValidation:
|
| 1873 |
+
def test_errors_are_cleared_after_loading_collection(self):
|
| 1874 |
+
def always_fail(val):
|
| 1875 |
+
raise ValidationError("lol")
|
| 1876 |
+
|
| 1877 |
+
class MySchema(Schema):
|
| 1878 |
+
foo = fields.Str(validate=always_fail)
|
| 1879 |
+
|
| 1880 |
+
schema = MySchema()
|
| 1881 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1882 |
+
schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True)
|
| 1883 |
+
errors = excinfo.value.messages
|
| 1884 |
+
assert len(errors[0]["foo"]) == 1
|
| 1885 |
+
assert len(errors[1]["foo"]) == 1
|
| 1886 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1887 |
+
schema.load({"foo": "bar"})
|
| 1888 |
+
errors = excinfo.value.messages
|
| 1889 |
+
assert len(errors["foo"]) == 1
|
| 1890 |
+
|
| 1891 |
+
def test_raises_error_with_list(self):
|
| 1892 |
+
def validator(val):
|
| 1893 |
+
raise ValidationError(["err1", "err2"])
|
| 1894 |
+
|
| 1895 |
+
class MySchema(Schema):
|
| 1896 |
+
foo = fields.Field(validate=validator)
|
| 1897 |
+
|
| 1898 |
+
s = MySchema()
|
| 1899 |
+
errors = s.validate({"foo": 42})
|
| 1900 |
+
assert errors["foo"] == ["err1", "err2"]
|
| 1901 |
+
|
| 1902 |
+
# https://github.com/marshmallow-code/marshmallow/issues/110
|
| 1903 |
+
def test_raises_error_with_dict(self):
|
| 1904 |
+
def validator(val):
|
| 1905 |
+
raise ValidationError({"code": "invalid_foo"})
|
| 1906 |
+
|
| 1907 |
+
class MySchema(Schema):
|
| 1908 |
+
foo = fields.Field(validate=validator)
|
| 1909 |
+
|
| 1910 |
+
s = MySchema()
|
| 1911 |
+
errors = s.validate({"foo": 42})
|
| 1912 |
+
assert errors["foo"] == [{"code": "invalid_foo"}]
|
| 1913 |
+
|
| 1914 |
+
def test_ignored_if_not_in_only(self):
|
| 1915 |
+
class MySchema(Schema):
|
| 1916 |
+
a = fields.Field()
|
| 1917 |
+
b = fields.Field()
|
| 1918 |
+
|
| 1919 |
+
@validates("a")
|
| 1920 |
+
def validate_a(self, val):
|
| 1921 |
+
raise ValidationError({"code": "invalid_a"})
|
| 1922 |
+
|
| 1923 |
+
@validates("b")
|
| 1924 |
+
def validate_b(self, val):
|
| 1925 |
+
raise ValidationError({"code": "invalid_b"})
|
| 1926 |
+
|
| 1927 |
+
s = MySchema(only=("b",))
|
| 1928 |
+
errors = s.validate({"b": "data"})
|
| 1929 |
+
assert errors == {"b": {"code": "invalid_b"}}
|
| 1930 |
+
|
| 1931 |
+
|
| 1932 |
+
def test_schema_repr():
|
| 1933 |
+
class MySchema(Schema):
|
| 1934 |
+
name = fields.String()
|
| 1935 |
+
|
| 1936 |
+
ser = MySchema(many=True)
|
| 1937 |
+
rep = repr(ser)
|
| 1938 |
+
assert "MySchema" in rep
|
| 1939 |
+
assert "many=True" in rep
|
| 1940 |
+
|
| 1941 |
+
|
| 1942 |
+
class TestNestedSchema:
|
| 1943 |
+
@pytest.fixture
|
| 1944 |
+
def user(self):
|
| 1945 |
+
return User(name="Monty", age=81)
|
| 1946 |
+
|
| 1947 |
+
@pytest.fixture
|
| 1948 |
+
def blog(self, user):
|
| 1949 |
+
col1 = User(name="Mick", age=123)
|
| 1950 |
+
col2 = User(name="Keith", age=456)
|
| 1951 |
+
blog = Blog(
|
| 1952 |
+
"Monty's blog",
|
| 1953 |
+
user=user,
|
| 1954 |
+
categories=["humor", "violence"],
|
| 1955 |
+
collaborators=[col1, col2],
|
| 1956 |
+
)
|
| 1957 |
+
return blog
|
| 1958 |
+
|
| 1959 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/64
|
| 1960 |
+
def test_nested_many_with_missing_attribute(self, user):
|
| 1961 |
+
class SimpleBlogSchema(Schema):
|
| 1962 |
+
title = fields.Str()
|
| 1963 |
+
wat = fields.Nested(UserSchema, many=True)
|
| 1964 |
+
|
| 1965 |
+
blog = Blog("Simple blog", user=user, collaborators=None)
|
| 1966 |
+
schema = SimpleBlogSchema()
|
| 1967 |
+
result = schema.dump(blog)
|
| 1968 |
+
assert "wat" not in result
|
| 1969 |
+
|
| 1970 |
+
def test_nested_with_attribute_none(self):
|
| 1971 |
+
class InnerSchema(Schema):
|
| 1972 |
+
bar = fields.Field()
|
| 1973 |
+
|
| 1974 |
+
class MySchema(Schema):
|
| 1975 |
+
foo = fields.Nested(InnerSchema)
|
| 1976 |
+
|
| 1977 |
+
class MySchema2(Schema):
|
| 1978 |
+
foo = fields.Nested(InnerSchema)
|
| 1979 |
+
|
| 1980 |
+
s = MySchema()
|
| 1981 |
+
result = s.dump({"foo": None})
|
| 1982 |
+
assert result["foo"] is None
|
| 1983 |
+
|
| 1984 |
+
s2 = MySchema2()
|
| 1985 |
+
result2 = s2.dump({"foo": None})
|
| 1986 |
+
assert result2["foo"] is None
|
| 1987 |
+
|
| 1988 |
+
def test_nested_field_does_not_validate_required(self):
|
| 1989 |
+
class BlogRequiredSchema(Schema):
|
| 1990 |
+
user = fields.Nested(UserSchema, required=True)
|
| 1991 |
+
|
| 1992 |
+
b = Blog("Authorless blog", user=None)
|
| 1993 |
+
BlogRequiredSchema().dump(b)
|
| 1994 |
+
|
| 1995 |
+
def test_nested_none(self):
|
| 1996 |
+
class BlogDefaultSchema(Schema):
|
| 1997 |
+
user = fields.Nested(UserSchema, dump_default=0)
|
| 1998 |
+
|
| 1999 |
+
b = Blog("Just the default blog", user=None)
|
| 2000 |
+
data = BlogDefaultSchema().dump(b)
|
| 2001 |
+
assert data["user"] is None
|
| 2002 |
+
|
| 2003 |
+
def test_nested(self, user, blog):
|
| 2004 |
+
blog_serializer = BlogSchema()
|
| 2005 |
+
serialized_blog = blog_serializer.dump(blog)
|
| 2006 |
+
user_serializer = UserSchema()
|
| 2007 |
+
serialized_user = user_serializer.dump(user)
|
| 2008 |
+
assert serialized_blog["user"] == serialized_user
|
| 2009 |
+
|
| 2010 |
+
with pytest.raises(ValidationError, match="email"):
|
| 2011 |
+
BlogSchema().load(
|
| 2012 |
+
{"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}}
|
| 2013 |
+
)
|
| 2014 |
+
|
| 2015 |
+
def test_nested_many_fields(self, blog):
|
| 2016 |
+
serialized_blog = BlogSchema().dump(blog)
|
| 2017 |
+
expected = [UserSchema().dump(col) for col in blog.collaborators]
|
| 2018 |
+
assert serialized_blog["collaborators"] == expected
|
| 2019 |
+
|
| 2020 |
+
def test_nested_meta_many(self, blog):
|
| 2021 |
+
serialized_blog = BlogUserMetaSchema().dump(blog)
|
| 2022 |
+
assert len(serialized_blog["collaborators"]) == 2
|
| 2023 |
+
expected = [UserMetaSchema().dump(col) for col in blog.collaborators]
|
| 2024 |
+
assert serialized_blog["collaborators"] == expected
|
| 2025 |
+
|
| 2026 |
+
def test_nested_only(self, blog):
|
| 2027 |
+
col1 = User(name="Mick", age=123, id_="abc")
|
| 2028 |
+
col2 = User(name="Keith", age=456, id_="def")
|
| 2029 |
+
blog.collaborators = [col1, col2]
|
| 2030 |
+
serialized_blog = BlogOnlySchema().dump(blog)
|
| 2031 |
+
assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}]
|
| 2032 |
+
|
| 2033 |
+
def test_exclude(self, blog):
|
| 2034 |
+
serialized = BlogSchemaExclude().dump(blog)
|
| 2035 |
+
assert "uppername" not in serialized["user"].keys()
|
| 2036 |
+
|
| 2037 |
+
def test_list_field(self, blog):
|
| 2038 |
+
serialized = BlogSchema().dump(blog)
|
| 2039 |
+
assert serialized["categories"] == ["humor", "violence"]
|
| 2040 |
+
|
| 2041 |
+
def test_nested_load_many(self):
|
| 2042 |
+
in_data = {
|
| 2043 |
+
"title": "Shine A Light",
|
| 2044 |
+
"collaborators": [
|
| 2045 |
+
{"name": "Mick", "email": "mick@stones.com"},
|
| 2046 |
+
{"name": "Keith", "email": "keith@stones.com"},
|
| 2047 |
+
],
|
| 2048 |
+
}
|
| 2049 |
+
data = BlogSchema().load(in_data)
|
| 2050 |
+
collabs = data["collaborators"]
|
| 2051 |
+
assert len(collabs) == 2
|
| 2052 |
+
assert all(type(each) is User for each in collabs)
|
| 2053 |
+
assert collabs[0].name == in_data["collaborators"][0]["name"]
|
| 2054 |
+
|
| 2055 |
+
def test_nested_errors(self):
|
| 2056 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2057 |
+
BlogSchema().load(
|
| 2058 |
+
{"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}}
|
| 2059 |
+
)
|
| 2060 |
+
errors = excinfo.value.messages
|
| 2061 |
+
assert "email" in errors["user"]
|
| 2062 |
+
assert len(errors["user"]["email"]) == 1
|
| 2063 |
+
assert "Not a valid email address." in errors["user"]["email"][0]
|
| 2064 |
+
# No problems with collaborators
|
| 2065 |
+
assert "collaborators" not in errors
|
| 2066 |
+
|
| 2067 |
+
def test_nested_method_field(self, blog):
|
| 2068 |
+
data = BlogSchema().dump(blog)
|
| 2069 |
+
assert data["user"]["is_old"]
|
| 2070 |
+
assert data["collaborators"][0]["is_old"]
|
| 2071 |
+
|
| 2072 |
+
def test_nested_function_field(self, blog, user):
|
| 2073 |
+
data = BlogSchema().dump(blog)
|
| 2074 |
+
assert data["user"]["lowername"] == user.name.lower()
|
| 2075 |
+
expected = blog.collaborators[0].name.lower()
|
| 2076 |
+
assert data["collaborators"][0]["lowername"] == expected
|
| 2077 |
+
|
| 2078 |
+
def test_serializer_meta_with_nested_fields(self, blog, user):
|
| 2079 |
+
data = BlogSchemaMeta().dump(blog)
|
| 2080 |
+
assert data["title"] == blog.title
|
| 2081 |
+
assert data["user"] == UserSchema().dump(user)
|
| 2082 |
+
assert data["collaborators"] == [
|
| 2083 |
+
UserSchema().dump(c) for c in blog.collaborators
|
| 2084 |
+
]
|
| 2085 |
+
assert data["categories"] == blog.categories
|
| 2086 |
+
|
| 2087 |
+
def test_serializer_with_nested_meta_fields(self, blog):
|
| 2088 |
+
# Schema has user = fields.Nested(UserMetaSerializer)
|
| 2089 |
+
s = BlogUserMetaSchema().dump(blog)
|
| 2090 |
+
assert s["user"] == UserMetaSchema().dump(blog.user)
|
| 2091 |
+
|
| 2092 |
+
def test_nested_fields_must_be_passed_a_serializer(self, blog):
|
| 2093 |
+
class BadNestedFieldSchema(BlogSchema):
|
| 2094 |
+
user = fields.Nested(fields.String)
|
| 2095 |
+
|
| 2096 |
+
with pytest.raises(ValueError):
|
| 2097 |
+
BadNestedFieldSchema().dump(blog)
|
| 2098 |
+
|
| 2099 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/188
|
| 2100 |
+
def test_invalid_type_passed_to_nested_field(self):
|
| 2101 |
+
class InnerSchema(Schema):
|
| 2102 |
+
foo = fields.Field()
|
| 2103 |
+
|
| 2104 |
+
class MySchema(Schema):
|
| 2105 |
+
inner = fields.Nested(InnerSchema, many=True)
|
| 2106 |
+
|
| 2107 |
+
sch = MySchema()
|
| 2108 |
+
|
| 2109 |
+
sch.load({"inner": [{"foo": 42}]})
|
| 2110 |
+
|
| 2111 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2112 |
+
sch.load({"inner": "invalid"})
|
| 2113 |
+
errors = excinfo.value.messages
|
| 2114 |
+
assert "inner" in errors
|
| 2115 |
+
assert errors["inner"] == ["Invalid type."]
|
| 2116 |
+
|
| 2117 |
+
class OuterSchema(Schema):
|
| 2118 |
+
inner = fields.Nested(InnerSchema)
|
| 2119 |
+
|
| 2120 |
+
schema = OuterSchema()
|
| 2121 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2122 |
+
schema.load({"inner": 1})
|
| 2123 |
+
errors = excinfo.value.messages
|
| 2124 |
+
assert errors["inner"]["_schema"] == ["Invalid input type."]
|
| 2125 |
+
|
| 2126 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/298
|
| 2127 |
+
def test_all_errors_on_many_nested_field_with_validates_decorator(self):
|
| 2128 |
+
class Inner(Schema):
|
| 2129 |
+
req = fields.Field(required=True)
|
| 2130 |
+
|
| 2131 |
+
class Outer(Schema):
|
| 2132 |
+
inner = fields.Nested(Inner, many=True)
|
| 2133 |
+
|
| 2134 |
+
@validates("inner")
|
| 2135 |
+
def validates_inner(self, data):
|
| 2136 |
+
raise ValidationError("not a chance")
|
| 2137 |
+
|
| 2138 |
+
outer = Outer()
|
| 2139 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2140 |
+
outer.load({"inner": [{}]})
|
| 2141 |
+
errors = excinfo.value.messages
|
| 2142 |
+
assert "inner" in errors
|
| 2143 |
+
assert "_schema" in errors["inner"]
|
| 2144 |
+
|
| 2145 |
+
@pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE))
|
| 2146 |
+
def test_nested_unknown_validation(self, unknown):
|
| 2147 |
+
class ChildSchema(Schema):
|
| 2148 |
+
num = fields.Int()
|
| 2149 |
+
|
| 2150 |
+
class ParentSchema(Schema):
|
| 2151 |
+
child = fields.Nested(ChildSchema, unknown=unknown)
|
| 2152 |
+
|
| 2153 |
+
data = {"child": {"num": 1, "extra": 1}}
|
| 2154 |
+
if unknown is None or unknown == RAISE:
|
| 2155 |
+
with pytest.raises(ValidationError) as exc:
|
| 2156 |
+
ParentSchema().load(data)
|
| 2157 |
+
assert exc.messages == {"child": {"extra": ["Unknown field."]}}
|
| 2158 |
+
else:
|
| 2159 |
+
output = {
|
| 2160 |
+
INCLUDE: {"child": {"num": 1, "extra": 1}},
|
| 2161 |
+
EXCLUDE: {"child": {"num": 1}},
|
| 2162 |
+
}[unknown]
|
| 2163 |
+
assert ParentSchema().load(data) == output
|
| 2164 |
+
|
| 2165 |
+
|
| 2166 |
+
class TestPluckSchema:
|
| 2167 |
+
@pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()])
|
| 2168 |
+
def test_pluck(self, user_schema, blog):
|
| 2169 |
+
class FlatBlogSchema(Schema):
|
| 2170 |
+
user = fields.Pluck(user_schema, "name")
|
| 2171 |
+
collaborators = fields.Pluck(user_schema, "name", many=True)
|
| 2172 |
+
|
| 2173 |
+
s = FlatBlogSchema()
|
| 2174 |
+
data = s.dump(blog)
|
| 2175 |
+
assert data["user"] == blog.user.name
|
| 2176 |
+
for i, name in enumerate(data["collaborators"]):
|
| 2177 |
+
assert name == blog.collaborators[i].name
|
| 2178 |
+
|
| 2179 |
+
def test_pluck_none(self, blog):
|
| 2180 |
+
class FlatBlogSchema(Schema):
|
| 2181 |
+
user = fields.Pluck(UserSchema, "name")
|
| 2182 |
+
collaborators = fields.Pluck(UserSchema, "name", many=True)
|
| 2183 |
+
|
| 2184 |
+
col1 = User(name="Mick", age=123)
|
| 2185 |
+
col2 = User(name="Keith", age=456)
|
| 2186 |
+
blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2])
|
| 2187 |
+
s = FlatBlogSchema()
|
| 2188 |
+
data = s.dump(blog)
|
| 2189 |
+
assert data["user"] == blog.user
|
| 2190 |
+
for i, name in enumerate(data["collaborators"]):
|
| 2191 |
+
assert name == blog.collaborators[i].name
|
| 2192 |
+
|
| 2193 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/800
|
| 2194 |
+
def test_pluck_with_data_key(self, blog):
|
| 2195 |
+
class UserSchema(Schema):
|
| 2196 |
+
name = fields.String(data_key="username")
|
| 2197 |
+
age = fields.Int()
|
| 2198 |
+
|
| 2199 |
+
class FlatBlogSchema(Schema):
|
| 2200 |
+
user = fields.Pluck(UserSchema, "name")
|
| 2201 |
+
collaborators = fields.Pluck(UserSchema, "name", many=True)
|
| 2202 |
+
|
| 2203 |
+
s = FlatBlogSchema()
|
| 2204 |
+
data = s.dump(blog)
|
| 2205 |
+
assert data["user"] == blog.user.name
|
| 2206 |
+
for i, name in enumerate(data["collaborators"]):
|
| 2207 |
+
assert name == blog.collaborators[i].name
|
| 2208 |
+
assert s.load(data) == {
|
| 2209 |
+
"user": {"name": "Monty"},
|
| 2210 |
+
"collaborators": [{"name": "Mick"}, {"name": "Keith"}],
|
| 2211 |
+
}
|
| 2212 |
+
|
| 2213 |
+
|
| 2214 |
+
class TestSelfReference:
|
| 2215 |
+
@pytest.fixture
|
| 2216 |
+
def employer(self):
|
| 2217 |
+
return User(name="Joe", age=59)
|
| 2218 |
+
|
| 2219 |
+
@pytest.fixture
|
| 2220 |
+
def user(self, employer):
|
| 2221 |
+
return User(name="Tom", employer=employer, age=28)
|
| 2222 |
+
|
| 2223 |
+
def test_nesting_schema_by_passing_lambda(self, user, employer):
|
| 2224 |
+
class SelfReferencingSchema(Schema):
|
| 2225 |
+
name = fields.Str()
|
| 2226 |
+
age = fields.Int()
|
| 2227 |
+
employer = fields.Nested(
|
| 2228 |
+
lambda: SelfReferencingSchema(exclude=("employer",))
|
| 2229 |
+
)
|
| 2230 |
+
|
| 2231 |
+
data = SelfReferencingSchema().dump(user)
|
| 2232 |
+
assert data["name"] == user.name
|
| 2233 |
+
assert data["employer"]["name"] == employer.name
|
| 2234 |
+
assert data["employer"]["age"] == employer.age
|
| 2235 |
+
|
| 2236 |
+
def test_nesting_schema_by_passing_class_name(self, user, employer):
|
| 2237 |
+
class SelfReferencingSchema(Schema):
|
| 2238 |
+
name = fields.Str()
|
| 2239 |
+
age = fields.Int()
|
| 2240 |
+
employer = fields.Nested("SelfReferencingSchema", exclude=("employer",))
|
| 2241 |
+
|
| 2242 |
+
data = SelfReferencingSchema().dump(user)
|
| 2243 |
+
assert data["name"] == user.name
|
| 2244 |
+
assert data["employer"]["name"] == employer.name
|
| 2245 |
+
assert data["employer"]["age"] == employer.age
|
| 2246 |
+
|
| 2247 |
+
def test_nesting_schema_self_string(self, user, employer):
|
| 2248 |
+
with pytest.warns(
|
| 2249 |
+
DeprecationWarning, match="Passing 'self' to `Nested` is deprecated"
|
| 2250 |
+
):
|
| 2251 |
+
|
| 2252 |
+
class SelfSchema(Schema):
|
| 2253 |
+
name = fields.String()
|
| 2254 |
+
age = fields.Integer()
|
| 2255 |
+
employer = fields.Nested("self", exclude=("employer",))
|
| 2256 |
+
|
| 2257 |
+
data = SelfSchema().dump(user)
|
| 2258 |
+
assert data["name"] == user.name
|
| 2259 |
+
assert data["employer"]["name"] == employer.name
|
| 2260 |
+
assert data["employer"]["age"] == employer.age
|
| 2261 |
+
|
| 2262 |
+
def test_nesting_within_itself_meta(self, user, employer):
|
| 2263 |
+
class SelfSchema(Schema):
|
| 2264 |
+
employer = fields.Nested(lambda: SelfSchema(exclude=("employer",)))
|
| 2265 |
+
|
| 2266 |
+
class Meta:
|
| 2267 |
+
additional = ("name", "age")
|
| 2268 |
+
|
| 2269 |
+
data = SelfSchema().dump(user)
|
| 2270 |
+
assert data["name"] == user.name
|
| 2271 |
+
assert data["age"] == user.age
|
| 2272 |
+
assert data["employer"]["name"] == employer.name
|
| 2273 |
+
assert data["employer"]["age"] == employer.age
|
| 2274 |
+
|
| 2275 |
+
def test_nested_self_with_only_param(self, user, employer):
|
| 2276 |
+
class SelfSchema(Schema):
|
| 2277 |
+
employer = fields.Nested(lambda: SelfSchema(only=("name",)))
|
| 2278 |
+
|
| 2279 |
+
class Meta:
|
| 2280 |
+
fields = ("name", "employer")
|
| 2281 |
+
|
| 2282 |
+
data = SelfSchema().dump(user)
|
| 2283 |
+
assert data["name"] == user.name
|
| 2284 |
+
assert data["employer"]["name"] == employer.name
|
| 2285 |
+
assert "age" not in data["employer"]
|
| 2286 |
+
|
| 2287 |
+
def test_multiple_pluck_self_lambda(self, user):
|
| 2288 |
+
class MultipleSelfSchema(Schema):
|
| 2289 |
+
emp = fields.Pluck(
|
| 2290 |
+
lambda: MultipleSelfSchema(), "name", attribute="employer"
|
| 2291 |
+
)
|
| 2292 |
+
rels = fields.Pluck(
|
| 2293 |
+
lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives"
|
| 2294 |
+
)
|
| 2295 |
+
|
| 2296 |
+
class Meta:
|
| 2297 |
+
fields = ("name", "emp", "rels")
|
| 2298 |
+
|
| 2299 |
+
schema = MultipleSelfSchema()
|
| 2300 |
+
user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)]
|
| 2301 |
+
data = schema.dump(user)
|
| 2302 |
+
assert len(data["rels"]) == len(user.relatives)
|
| 2303 |
+
relative = data["rels"][0]
|
| 2304 |
+
assert relative == user.relatives[0].name
|
| 2305 |
+
|
| 2306 |
+
def test_multiple_pluck_self_string(self, user):
|
| 2307 |
+
with pytest.warns(
|
| 2308 |
+
DeprecationWarning, match="Passing 'self' to `Nested` is deprecated"
|
| 2309 |
+
):
|
| 2310 |
+
|
| 2311 |
+
class MultipleSelfSchema(Schema):
|
| 2312 |
+
emp = fields.Pluck("self", "name", attribute="employer")
|
| 2313 |
+
rels = fields.Pluck("self", "name", many=True, attribute="relatives")
|
| 2314 |
+
|
| 2315 |
+
class Meta:
|
| 2316 |
+
fields = ("name", "emp", "rels")
|
| 2317 |
+
|
| 2318 |
+
schema = MultipleSelfSchema()
|
| 2319 |
+
user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)]
|
| 2320 |
+
data = schema.dump(user)
|
| 2321 |
+
assert len(data["rels"]) == len(user.relatives)
|
| 2322 |
+
relative = data["rels"][0]
|
| 2323 |
+
assert relative == user.relatives[0].name
|
| 2324 |
+
|
| 2325 |
+
def test_nested_self_many_lambda(self):
|
| 2326 |
+
class SelfManySchema(Schema):
|
| 2327 |
+
relatives = fields.Nested(lambda: SelfManySchema(), many=True)
|
| 2328 |
+
|
| 2329 |
+
class Meta:
|
| 2330 |
+
additional = ("name", "age")
|
| 2331 |
+
|
| 2332 |
+
person = User(name="Foo")
|
| 2333 |
+
person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)]
|
| 2334 |
+
data = SelfManySchema().dump(person)
|
| 2335 |
+
assert data["name"] == person.name
|
| 2336 |
+
assert len(data["relatives"]) == len(person.relatives)
|
| 2337 |
+
assert data["relatives"][0]["name"] == person.relatives[0].name
|
| 2338 |
+
assert data["relatives"][0]["age"] == person.relatives[0].age
|
| 2339 |
+
|
| 2340 |
+
def test_nested_self_many_string(self):
|
| 2341 |
+
with pytest.warns(
|
| 2342 |
+
DeprecationWarning, match="Passing 'self' to `Nested` is deprecated"
|
| 2343 |
+
):
|
| 2344 |
+
|
| 2345 |
+
class SelfManySchema(Schema):
|
| 2346 |
+
relatives = fields.Nested("self", many=True)
|
| 2347 |
+
|
| 2348 |
+
class Meta:
|
| 2349 |
+
additional = ("name", "age")
|
| 2350 |
+
|
| 2351 |
+
person = User(name="Foo")
|
| 2352 |
+
person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)]
|
| 2353 |
+
data = SelfManySchema().dump(person)
|
| 2354 |
+
assert data["name"] == person.name
|
| 2355 |
+
assert len(data["relatives"]) == len(person.relatives)
|
| 2356 |
+
assert data["relatives"][0]["name"] == person.relatives[0].name
|
| 2357 |
+
assert data["relatives"][0]["age"] == person.relatives[0].age
|
| 2358 |
+
|
| 2359 |
+
def test_nested_self_list(self):
|
| 2360 |
+
class SelfListSchema(Schema):
|
| 2361 |
+
relatives = fields.List(fields.Nested(lambda: SelfListSchema()))
|
| 2362 |
+
|
| 2363 |
+
class Meta:
|
| 2364 |
+
additional = ("name", "age")
|
| 2365 |
+
|
| 2366 |
+
person = User(name="Foo")
|
| 2367 |
+
person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)]
|
| 2368 |
+
data = SelfListSchema().dump(person)
|
| 2369 |
+
assert data["name"] == person.name
|
| 2370 |
+
assert len(data["relatives"]) == len(person.relatives)
|
| 2371 |
+
assert data["relatives"][0]["name"] == person.relatives[0].name
|
| 2372 |
+
assert data["relatives"][0]["age"] == person.relatives[0].age
|
| 2373 |
+
|
| 2374 |
+
def test_nested_self_list_string(self):
|
| 2375 |
+
with pytest.warns(
|
| 2376 |
+
DeprecationWarning, match="Passing 'self' to `Nested` is deprecated"
|
| 2377 |
+
):
|
| 2378 |
+
|
| 2379 |
+
class SelfListSchema(Schema):
|
| 2380 |
+
relatives = fields.List(fields.Nested("self"))
|
| 2381 |
+
|
| 2382 |
+
class Meta:
|
| 2383 |
+
additional = ("name", "age")
|
| 2384 |
+
|
| 2385 |
+
person = User(name="Foo")
|
| 2386 |
+
person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)]
|
| 2387 |
+
data = SelfListSchema().dump(person)
|
| 2388 |
+
assert data["name"] == person.name
|
| 2389 |
+
assert len(data["relatives"]) == len(person.relatives)
|
| 2390 |
+
assert data["relatives"][0]["name"] == person.relatives[0].name
|
| 2391 |
+
assert data["relatives"][0]["age"] == person.relatives[0].age
|
| 2392 |
+
|
| 2393 |
+
|
| 2394 |
+
class RequiredUserSchema(Schema):
|
| 2395 |
+
name = fields.Field(required=True)
|
| 2396 |
+
|
| 2397 |
+
|
| 2398 |
+
def test_serialization_with_required_field():
|
| 2399 |
+
user = User(name=None)
|
| 2400 |
+
RequiredUserSchema().dump(user)
|
| 2401 |
+
|
| 2402 |
+
|
| 2403 |
+
def test_deserialization_with_required_field():
|
| 2404 |
+
in_data = {}
|
| 2405 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2406 |
+
RequiredUserSchema().load(in_data)
|
| 2407 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 2408 |
+
assert "name" in errors
|
| 2409 |
+
assert "Missing data for required field." in errors["name"]
|
| 2410 |
+
# field value should also not be in output data
|
| 2411 |
+
assert "name" not in data
|
| 2412 |
+
|
| 2413 |
+
|
| 2414 |
+
def test_deserialization_with_required_field_and_custom_validator():
|
| 2415 |
+
class ValidatingSchema(Schema):
|
| 2416 |
+
color = fields.String(
|
| 2417 |
+
required=True,
|
| 2418 |
+
validate=lambda x: x.lower() == "red" or x.lower() == "blue",
|
| 2419 |
+
error_messages={"validator_failed": "Color must be red or blue"},
|
| 2420 |
+
)
|
| 2421 |
+
|
| 2422 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2423 |
+
ValidatingSchema().load({"name": "foo"})
|
| 2424 |
+
errors = excinfo.value.messages
|
| 2425 |
+
assert errors
|
| 2426 |
+
assert "color" in errors
|
| 2427 |
+
assert "Missing data for required field." in errors["color"]
|
| 2428 |
+
|
| 2429 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2430 |
+
ValidatingSchema().load({"color": "green"})
|
| 2431 |
+
errors = excinfo.value.messages
|
| 2432 |
+
assert "color" in errors
|
| 2433 |
+
assert "Color must be red or blue" in errors["color"]
|
| 2434 |
+
|
| 2435 |
+
|
| 2436 |
+
class UserContextSchema(Schema):
|
| 2437 |
+
is_owner = fields.Method("get_is_owner")
|
| 2438 |
+
is_collab = fields.Function(lambda user, ctx: user in ctx["blog"])
|
| 2439 |
+
|
| 2440 |
+
def get_is_owner(self, user):
|
| 2441 |
+
return self.context["blog"].user.name == user.name
|
| 2442 |
+
|
| 2443 |
+
|
| 2444 |
+
class TestContext:
|
| 2445 |
+
def test_context_method(self):
|
| 2446 |
+
owner = User("Joe")
|
| 2447 |
+
blog = Blog(title="Joe Blog", user=owner)
|
| 2448 |
+
context = {"blog": blog}
|
| 2449 |
+
serializer = UserContextSchema()
|
| 2450 |
+
serializer.context = context
|
| 2451 |
+
data = serializer.dump(owner)
|
| 2452 |
+
assert data["is_owner"] is True
|
| 2453 |
+
nonowner = User("Fred")
|
| 2454 |
+
data = serializer.dump(nonowner)
|
| 2455 |
+
assert data["is_owner"] is False
|
| 2456 |
+
|
| 2457 |
+
def test_context_method_function(self):
|
| 2458 |
+
owner = User("Fred")
|
| 2459 |
+
blog = Blog("Killer Queen", user=owner)
|
| 2460 |
+
collab = User("Brian")
|
| 2461 |
+
blog.collaborators.append(collab)
|
| 2462 |
+
context = {"blog": blog}
|
| 2463 |
+
serializer = UserContextSchema()
|
| 2464 |
+
serializer.context = context
|
| 2465 |
+
data = serializer.dump(collab)
|
| 2466 |
+
assert data["is_collab"] is True
|
| 2467 |
+
noncollab = User("Foo")
|
| 2468 |
+
data = serializer.dump(noncollab)
|
| 2469 |
+
assert data["is_collab"] is False
|
| 2470 |
+
|
| 2471 |
+
def test_function_field_raises_error_when_context_not_available(self):
|
| 2472 |
+
# only has a function field
|
| 2473 |
+
class UserFunctionContextSchema(Schema):
|
| 2474 |
+
is_collab = fields.Function(lambda user, ctx: user in ctx["blog"])
|
| 2475 |
+
|
| 2476 |
+
owner = User("Joe")
|
| 2477 |
+
serializer = UserFunctionContextSchema()
|
| 2478 |
+
# no context
|
| 2479 |
+
serializer.context = None
|
| 2480 |
+
msg = "No context available for Function field {!r}".format("is_collab")
|
| 2481 |
+
with pytest.raises(ValidationError, match=msg):
|
| 2482 |
+
serializer.dump(owner)
|
| 2483 |
+
|
| 2484 |
+
def test_function_field_handles_bound_serializer(self):
|
| 2485 |
+
class SerializeA:
|
| 2486 |
+
def __call__(self, value):
|
| 2487 |
+
return "value"
|
| 2488 |
+
|
| 2489 |
+
serialize = SerializeA()
|
| 2490 |
+
|
| 2491 |
+
# only has a function field
|
| 2492 |
+
class UserFunctionContextSchema(Schema):
|
| 2493 |
+
is_collab = fields.Function(serialize)
|
| 2494 |
+
|
| 2495 |
+
owner = User("Joe")
|
| 2496 |
+
serializer = UserFunctionContextSchema()
|
| 2497 |
+
# no context
|
| 2498 |
+
serializer.context = None
|
| 2499 |
+
data = serializer.dump(owner)
|
| 2500 |
+
assert data["is_collab"] == "value"
|
| 2501 |
+
|
| 2502 |
+
def test_fields_context(self):
|
| 2503 |
+
class CSchema(Schema):
|
| 2504 |
+
name = fields.String()
|
| 2505 |
+
|
| 2506 |
+
ser = CSchema()
|
| 2507 |
+
ser.context["foo"] = 42
|
| 2508 |
+
|
| 2509 |
+
assert ser.fields["name"].context == {"foo": 42}
|
| 2510 |
+
|
| 2511 |
+
def test_nested_fields_inherit_context(self):
|
| 2512 |
+
class InnerSchema(Schema):
|
| 2513 |
+
likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"])
|
| 2514 |
+
|
| 2515 |
+
class CSchema(Schema):
|
| 2516 |
+
inner = fields.Nested(InnerSchema)
|
| 2517 |
+
|
| 2518 |
+
ser = CSchema()
|
| 2519 |
+
ser.context["info"] = "i like bikes"
|
| 2520 |
+
obj = {"inner": {}}
|
| 2521 |
+
result = ser.dump(obj)
|
| 2522 |
+
assert result["inner"]["likes_bikes"] is True
|
| 2523 |
+
|
| 2524 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/820
|
| 2525 |
+
def test_nested_list_fields_inherit_context(self):
|
| 2526 |
+
class InnerSchema(Schema):
|
| 2527 |
+
foo = fields.Field()
|
| 2528 |
+
|
| 2529 |
+
@validates("foo")
|
| 2530 |
+
def validate_foo(self, value):
|
| 2531 |
+
if "foo_context" not in self.context:
|
| 2532 |
+
raise ValidationError("Missing context")
|
| 2533 |
+
|
| 2534 |
+
class OuterSchema(Schema):
|
| 2535 |
+
bars = fields.List(fields.Nested(InnerSchema()))
|
| 2536 |
+
|
| 2537 |
+
inner = InnerSchema()
|
| 2538 |
+
inner.context["foo_context"] = "foo"
|
| 2539 |
+
assert inner.load({"foo": 42})
|
| 2540 |
+
|
| 2541 |
+
outer = OuterSchema()
|
| 2542 |
+
outer.context["foo_context"] = "foo"
|
| 2543 |
+
assert outer.load({"bars": [{"foo": 42}]})
|
| 2544 |
+
|
| 2545 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/820
|
| 2546 |
+
def test_nested_dict_fields_inherit_context(self):
|
| 2547 |
+
class InnerSchema(Schema):
|
| 2548 |
+
foo = fields.Field()
|
| 2549 |
+
|
| 2550 |
+
@validates("foo")
|
| 2551 |
+
def validate_foo(self, value):
|
| 2552 |
+
if "foo_context" not in self.context:
|
| 2553 |
+
raise ValidationError("Missing context")
|
| 2554 |
+
|
| 2555 |
+
class OuterSchema(Schema):
|
| 2556 |
+
bars = fields.Dict(values=fields.Nested(InnerSchema()))
|
| 2557 |
+
|
| 2558 |
+
inner = InnerSchema()
|
| 2559 |
+
inner.context["foo_context"] = "foo"
|
| 2560 |
+
assert inner.load({"foo": 42})
|
| 2561 |
+
|
| 2562 |
+
outer = OuterSchema()
|
| 2563 |
+
outer.context["foo_context"] = "foo"
|
| 2564 |
+
assert outer.load({"bars": {"test": {"foo": 42}}})
|
| 2565 |
+
|
| 2566 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404
|
| 2567 |
+
def test_nested_field_with_unpicklable_object_in_context(self):
|
| 2568 |
+
class Unpicklable:
|
| 2569 |
+
def __deepcopy__(self, _):
|
| 2570 |
+
raise NotImplementedError
|
| 2571 |
+
|
| 2572 |
+
class InnerSchema(Schema):
|
| 2573 |
+
foo = fields.Field()
|
| 2574 |
+
|
| 2575 |
+
class OuterSchema(Schema):
|
| 2576 |
+
inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()}))
|
| 2577 |
+
|
| 2578 |
+
outer = OuterSchema()
|
| 2579 |
+
obj = {"inner": {"foo": 42}}
|
| 2580 |
+
assert outer.dump(obj)
|
| 2581 |
+
|
| 2582 |
+
|
| 2583 |
+
def test_serializer_can_specify_nested_object_as_attribute(blog):
|
| 2584 |
+
class BlogUsernameSchema(Schema):
|
| 2585 |
+
author_name = fields.String(attribute="user.name")
|
| 2586 |
+
|
| 2587 |
+
ser = BlogUsernameSchema()
|
| 2588 |
+
result = ser.dump(blog)
|
| 2589 |
+
assert result["author_name"] == blog.user.name
|
| 2590 |
+
|
| 2591 |
+
|
| 2592 |
+
class TestFieldInheritance:
|
| 2593 |
+
def test_inherit_fields_from_schema_subclass(self):
|
| 2594 |
+
expected = {
|
| 2595 |
+
"field_a": fields.Number(),
|
| 2596 |
+
"field_b": fields.Number(),
|
| 2597 |
+
}
|
| 2598 |
+
|
| 2599 |
+
class SerializerA(Schema):
|
| 2600 |
+
field_a = expected["field_a"]
|
| 2601 |
+
|
| 2602 |
+
class SerializerB(SerializerA):
|
| 2603 |
+
field_b = expected["field_b"]
|
| 2604 |
+
|
| 2605 |
+
assert SerializerB._declared_fields == expected
|
| 2606 |
+
|
| 2607 |
+
def test_inherit_fields_from_non_schema_subclass(self):
|
| 2608 |
+
expected = {
|
| 2609 |
+
"field_a": fields.Number(),
|
| 2610 |
+
"field_b": fields.Number(),
|
| 2611 |
+
}
|
| 2612 |
+
|
| 2613 |
+
class PlainBaseClass:
|
| 2614 |
+
field_a = expected["field_a"]
|
| 2615 |
+
|
| 2616 |
+
class SerializerB1(Schema, PlainBaseClass):
|
| 2617 |
+
field_b = expected["field_b"]
|
| 2618 |
+
|
| 2619 |
+
class SerializerB2(PlainBaseClass, Schema):
|
| 2620 |
+
field_b = expected["field_b"]
|
| 2621 |
+
|
| 2622 |
+
assert SerializerB1._declared_fields == expected
|
| 2623 |
+
assert SerializerB2._declared_fields == expected
|
| 2624 |
+
|
| 2625 |
+
def test_inheritance_follows_mro(self):
|
| 2626 |
+
expected = {
|
| 2627 |
+
"field_a": fields.String(),
|
| 2628 |
+
"field_b": fields.String(),
|
| 2629 |
+
"field_c": fields.String(),
|
| 2630 |
+
"field_d": fields.String(),
|
| 2631 |
+
}
|
| 2632 |
+
# Diamond inheritance graph
|
| 2633 |
+
# MRO: D -> B -> C -> A
|
| 2634 |
+
|
| 2635 |
+
class SerializerA(Schema):
|
| 2636 |
+
field_a = expected["field_a"]
|
| 2637 |
+
|
| 2638 |
+
class SerializerB(SerializerA):
|
| 2639 |
+
field_b = expected["field_b"]
|
| 2640 |
+
|
| 2641 |
+
class SerializerC(SerializerA):
|
| 2642 |
+
field_c = expected["field_c"]
|
| 2643 |
+
|
| 2644 |
+
class SerializerD(SerializerB, SerializerC):
|
| 2645 |
+
field_d = expected["field_d"]
|
| 2646 |
+
|
| 2647 |
+
assert SerializerD._declared_fields == expected
|
| 2648 |
+
|
| 2649 |
+
|
| 2650 |
+
def get_from_dict(schema, obj, key, default=None):
|
| 2651 |
+
return obj.get("_" + key, default)
|
| 2652 |
+
|
| 2653 |
+
|
| 2654 |
+
class TestGetAttribute:
|
| 2655 |
+
def test_get_attribute_is_used(self):
|
| 2656 |
+
class UserDictSchema(Schema):
|
| 2657 |
+
name = fields.Str()
|
| 2658 |
+
email = fields.Email()
|
| 2659 |
+
|
| 2660 |
+
def get_attribute(self, obj, attr, default):
|
| 2661 |
+
return get_from_dict(self, obj, attr, default)
|
| 2662 |
+
|
| 2663 |
+
user_dict = {"_name": "joe", "_email": "joe@shmoe.com"}
|
| 2664 |
+
schema = UserDictSchema()
|
| 2665 |
+
result = schema.dump(user_dict)
|
| 2666 |
+
assert result["name"] == user_dict["_name"]
|
| 2667 |
+
assert result["email"] == user_dict["_email"]
|
| 2668 |
+
# can't serialize User object
|
| 2669 |
+
user = User(name="joe", email="joe@shmoe.com")
|
| 2670 |
+
with pytest.raises(AttributeError):
|
| 2671 |
+
schema.dump(user)
|
| 2672 |
+
|
| 2673 |
+
def test_get_attribute_with_many(self):
|
| 2674 |
+
class UserDictSchema(Schema):
|
| 2675 |
+
name = fields.Str()
|
| 2676 |
+
email = fields.Email()
|
| 2677 |
+
|
| 2678 |
+
def get_attribute(self, obj, attr, default):
|
| 2679 |
+
return get_from_dict(self, obj, attr, default)
|
| 2680 |
+
|
| 2681 |
+
user_dicts = [
|
| 2682 |
+
{"_name": "joe", "_email": "joe@shmoe.com"},
|
| 2683 |
+
{"_name": "jane", "_email": "jane@shmane.com"},
|
| 2684 |
+
]
|
| 2685 |
+
schema = UserDictSchema(many=True)
|
| 2686 |
+
results = schema.dump(user_dicts)
|
| 2687 |
+
for result, user_dict in zip(results, user_dicts):
|
| 2688 |
+
assert result["name"] == user_dict["_name"]
|
| 2689 |
+
assert result["email"] == user_dict["_email"]
|
| 2690 |
+
# can't serialize User object
|
| 2691 |
+
users = [
|
| 2692 |
+
User(name="joe", email="joe@shmoe.com"),
|
| 2693 |
+
User(name="jane", email="jane@shmane.com"),
|
| 2694 |
+
]
|
| 2695 |
+
with pytest.raises(AttributeError):
|
| 2696 |
+
schema.dump(users)
|
| 2697 |
+
|
| 2698 |
+
|
| 2699 |
+
class TestRequiredFields:
|
| 2700 |
+
class StringSchema(Schema):
|
| 2701 |
+
required_field = fields.Str(required=True)
|
| 2702 |
+
allow_none_field = fields.Str(allow_none=True)
|
| 2703 |
+
allow_none_required_field = fields.Str(required=True, allow_none=True)
|
| 2704 |
+
|
| 2705 |
+
@pytest.fixture()
|
| 2706 |
+
def string_schema(self):
|
| 2707 |
+
return self.StringSchema()
|
| 2708 |
+
|
| 2709 |
+
@pytest.fixture()
|
| 2710 |
+
def data(self):
|
| 2711 |
+
return dict(
|
| 2712 |
+
required_field="foo",
|
| 2713 |
+
allow_none_field="bar",
|
| 2714 |
+
allow_none_required_field="one",
|
| 2715 |
+
)
|
| 2716 |
+
|
| 2717 |
+
def test_required_string_field_missing(self, string_schema, data):
|
| 2718 |
+
del data["required_field"]
|
| 2719 |
+
errors = string_schema.validate(data)
|
| 2720 |
+
assert errors["required_field"] == ["Missing data for required field."]
|
| 2721 |
+
|
| 2722 |
+
def test_required_string_field_failure(self, string_schema, data):
|
| 2723 |
+
data["required_field"] = None
|
| 2724 |
+
errors = string_schema.validate(data)
|
| 2725 |
+
assert errors["required_field"] == ["Field may not be null."]
|
| 2726 |
+
|
| 2727 |
+
def test_allow_none_param(self, string_schema, data):
|
| 2728 |
+
data["allow_none_field"] = None
|
| 2729 |
+
errors = string_schema.validate(data)
|
| 2730 |
+
assert errors == {}
|
| 2731 |
+
|
| 2732 |
+
data["allow_none_required_field"] = None
|
| 2733 |
+
string_schema.validate(data)
|
| 2734 |
+
|
| 2735 |
+
del data["allow_none_required_field"]
|
| 2736 |
+
errors = string_schema.validate(data)
|
| 2737 |
+
assert "allow_none_required_field" in errors
|
| 2738 |
+
|
| 2739 |
+
def test_allow_none_custom_message(self, data):
|
| 2740 |
+
class MySchema(Schema):
|
| 2741 |
+
allow_none_field = fields.Field(
|
| 2742 |
+
allow_none=False, error_messages={"null": "<custom>"}
|
| 2743 |
+
)
|
| 2744 |
+
|
| 2745 |
+
schema = MySchema()
|
| 2746 |
+
errors = schema.validate({"allow_none_field": None})
|
| 2747 |
+
assert errors["allow_none_field"][0] == "<custom>"
|
| 2748 |
+
|
| 2749 |
+
|
| 2750 |
+
class TestDefaults:
|
| 2751 |
+
class MySchema(Schema):
|
| 2752 |
+
int_no_default = fields.Int(allow_none=True)
|
| 2753 |
+
str_no_default = fields.Str(allow_none=True)
|
| 2754 |
+
list_no_default = fields.List(fields.Str, allow_none=True)
|
| 2755 |
+
nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True)
|
| 2756 |
+
|
| 2757 |
+
int_with_default = fields.Int(allow_none=True, dump_default=42)
|
| 2758 |
+
str_with_default = fields.Str(allow_none=True, dump_default="foo")
|
| 2759 |
+
|
| 2760 |
+
@pytest.fixture()
|
| 2761 |
+
def schema(self):
|
| 2762 |
+
return self.MySchema()
|
| 2763 |
+
|
| 2764 |
+
@pytest.fixture()
|
| 2765 |
+
def data(self):
|
| 2766 |
+
return dict(
|
| 2767 |
+
int_no_default=None,
|
| 2768 |
+
str_no_default=None,
|
| 2769 |
+
list_no_default=None,
|
| 2770 |
+
nested_no_default=None,
|
| 2771 |
+
int_with_default=None,
|
| 2772 |
+
str_with_default=None,
|
| 2773 |
+
)
|
| 2774 |
+
|
| 2775 |
+
def test_missing_inputs_are_excluded_from_dump_output(self, schema, data):
|
| 2776 |
+
for key in [
|
| 2777 |
+
"int_no_default",
|
| 2778 |
+
"str_no_default",
|
| 2779 |
+
"list_no_default",
|
| 2780 |
+
"nested_no_default",
|
| 2781 |
+
]:
|
| 2782 |
+
d = data.copy()
|
| 2783 |
+
del d[key]
|
| 2784 |
+
result = schema.dump(d)
|
| 2785 |
+
# the missing key is not in the serialized result
|
| 2786 |
+
assert key not in result
|
| 2787 |
+
# the rest of the keys are in the result
|
| 2788 |
+
assert all(k in result for k in d.keys())
|
| 2789 |
+
|
| 2790 |
+
def test_none_is_serialized_to_none(self, schema, data):
|
| 2791 |
+
errors = schema.validate(data)
|
| 2792 |
+
assert errors == {}
|
| 2793 |
+
result = schema.dump(data)
|
| 2794 |
+
for key in data.keys():
|
| 2795 |
+
msg = f"result[{key!r}] should be None"
|
| 2796 |
+
assert result[key] is None, msg
|
| 2797 |
+
|
| 2798 |
+
def test_default_and_value_missing(self, schema, data):
|
| 2799 |
+
del data["int_with_default"]
|
| 2800 |
+
del data["str_with_default"]
|
| 2801 |
+
result = schema.dump(data)
|
| 2802 |
+
assert result["int_with_default"] == 42
|
| 2803 |
+
assert result["str_with_default"] == "foo"
|
| 2804 |
+
|
| 2805 |
+
def test_loading_none(self, schema, data):
|
| 2806 |
+
result = schema.load(data)
|
| 2807 |
+
for key in data.keys():
|
| 2808 |
+
assert result[key] is None
|
| 2809 |
+
|
| 2810 |
+
def test_missing_inputs_are_excluded_from_load_output(self, schema, data):
|
| 2811 |
+
for key in [
|
| 2812 |
+
"int_no_default",
|
| 2813 |
+
"str_no_default",
|
| 2814 |
+
"list_no_default",
|
| 2815 |
+
"nested_no_default",
|
| 2816 |
+
]:
|
| 2817 |
+
d = data.copy()
|
| 2818 |
+
del d[key]
|
| 2819 |
+
result = schema.load(d)
|
| 2820 |
+
# the missing key is not in the deserialized result
|
| 2821 |
+
assert key not in result
|
| 2822 |
+
# the rest of the keys are in the result
|
| 2823 |
+
assert all(k in result for k in d.keys())
|
| 2824 |
+
|
| 2825 |
+
|
| 2826 |
+
class TestLoadOnly:
|
| 2827 |
+
class MySchema(Schema):
|
| 2828 |
+
class Meta:
|
| 2829 |
+
load_only = ("str_load_only",)
|
| 2830 |
+
dump_only = ("str_dump_only",)
|
| 2831 |
+
|
| 2832 |
+
str_dump_only = fields.String()
|
| 2833 |
+
str_load_only = fields.String()
|
| 2834 |
+
str_regular = fields.String()
|
| 2835 |
+
|
| 2836 |
+
@pytest.fixture()
|
| 2837 |
+
def schema(self):
|
| 2838 |
+
return self.MySchema()
|
| 2839 |
+
|
| 2840 |
+
@pytest.fixture()
|
| 2841 |
+
def data(self):
|
| 2842 |
+
return dict(
|
| 2843 |
+
str_dump_only="Dump Only",
|
| 2844 |
+
str_load_only="Load Only",
|
| 2845 |
+
str_regular="Regular String",
|
| 2846 |
+
)
|
| 2847 |
+
|
| 2848 |
+
def test_load_only(self, schema, data):
|
| 2849 |
+
result = schema.dump(data)
|
| 2850 |
+
assert "str_load_only" not in result
|
| 2851 |
+
assert "str_dump_only" in result
|
| 2852 |
+
assert "str_regular" in result
|
| 2853 |
+
|
| 2854 |
+
def test_dump_only(self, schema, data):
|
| 2855 |
+
result = schema.load(data, unknown=EXCLUDE)
|
| 2856 |
+
assert "str_dump_only" not in result
|
| 2857 |
+
assert "str_load_only" in result
|
| 2858 |
+
assert "str_regular" in result
|
| 2859 |
+
|
| 2860 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/pull/765
|
| 2861 |
+
def test_url_field_requre_tld_false(self):
|
| 2862 |
+
class NoTldTestSchema(Schema):
|
| 2863 |
+
url = fields.Url(require_tld=False, schemes=["marshmallow"])
|
| 2864 |
+
|
| 2865 |
+
schema = NoTldTestSchema()
|
| 2866 |
+
data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"}
|
| 2867 |
+
result = schema.load(data_with_no_top_level_domain)
|
| 2868 |
+
assert result == data_with_no_top_level_domain
|
| 2869 |
+
|
| 2870 |
+
|
| 2871 |
+
class TestFromDict:
|
| 2872 |
+
def test_generates_schema(self):
|
| 2873 |
+
MySchema = Schema.from_dict({"foo": fields.Str()})
|
| 2874 |
+
assert issubclass(MySchema, Schema)
|
| 2875 |
+
|
| 2876 |
+
def test_name(self):
|
| 2877 |
+
MySchema = Schema.from_dict({"foo": fields.Str()})
|
| 2878 |
+
assert "GeneratedSchema" in repr(MySchema)
|
| 2879 |
+
SchemaWithName = Schema.from_dict(
|
| 2880 |
+
{"foo": fields.Int()}, name="MyGeneratedSchema"
|
| 2881 |
+
)
|
| 2882 |
+
assert "MyGeneratedSchema" in repr(SchemaWithName)
|
| 2883 |
+
|
| 2884 |
+
def test_generated_schemas_are_not_registered(self):
|
| 2885 |
+
n_registry_entries = len(class_registry._registry)
|
| 2886 |
+
Schema.from_dict({"foo": fields.Str()})
|
| 2887 |
+
Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema")
|
| 2888 |
+
assert len(class_registry._registry) == n_registry_entries
|
| 2889 |
+
with pytest.raises(RegistryError):
|
| 2890 |
+
class_registry.get_class("GeneratedSchema")
|
| 2891 |
+
with pytest.raises(RegistryError):
|
| 2892 |
+
class_registry.get_class("MyGeneratedSchema")
|
| 2893 |
+
|
| 2894 |
+
def test_meta_options_are_applied(self):
|
| 2895 |
+
class OrderedSchema(Schema):
|
| 2896 |
+
class Meta:
|
| 2897 |
+
ordered = True
|
| 2898 |
+
load_only = ("bar",)
|
| 2899 |
+
|
| 2900 |
+
OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()})
|
| 2901 |
+
dumped = OSchema().dump({"foo": 42, "bar": 24})
|
| 2902 |
+
assert isinstance(dumped, OrderedDict)
|
| 2903 |
+
assert "bar" not in dumped
|
| 2904 |
+
|
| 2905 |
+
|
| 2906 |
+
def test_class_registry_returns_schema_type():
|
| 2907 |
+
class DefinitelyUniqueSchema(Schema):
|
| 2908 |
+
"""
|
| 2909 |
+
Just a schema
|
| 2910 |
+
"""
|
| 2911 |
+
|
| 2912 |
+
SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__)
|
| 2913 |
+
assert SchemaClass is DefinitelyUniqueSchema
|
| 2914 |
+
|
| 2915 |
+
|
| 2916 |
+
@pytest.mark.parametrize("usage_location", ["meta", "init", "load"])
|
| 2917 |
+
def test_unknown_parameter_value_is_validated(usage_location):
|
| 2918 |
+
class MySchema(Schema):
|
| 2919 |
+
foo = fields.String()
|
| 2920 |
+
|
| 2921 |
+
with pytest.raises(
|
| 2922 |
+
ValueError,
|
| 2923 |
+
match="Object 'badval' is not a valid value for the 'unknown' parameter",
|
| 2924 |
+
):
|
| 2925 |
+
# Meta.unknown setting gets caught at class creation time, since that's when
|
| 2926 |
+
# metaclass __new__ runs
|
| 2927 |
+
if usage_location == "meta":
|
| 2928 |
+
|
| 2929 |
+
class SubSchema(MySchema):
|
| 2930 |
+
class Meta:
|
| 2931 |
+
unknown = "badval"
|
| 2932 |
+
|
| 2933 |
+
# usages in init and load are caught at call time, as expected
|
| 2934 |
+
elif usage_location == "init":
|
| 2935 |
+
MySchema(unknown="badval")
|
| 2936 |
+
else:
|
| 2937 |
+
MySchema().load({"foo": "bar"}, unknown="badval")
|
| 2938 |
+
|
| 2939 |
+
|
| 2940 |
+
@pytest.mark.parametrize("dict_cls", (dict, OrderedDict))
|
| 2941 |
+
def test_set_dict_class(dict_cls):
|
| 2942 |
+
"""Demonstrate how to specify dict_class as class attribute"""
|
| 2943 |
+
|
| 2944 |
+
class MySchema(Schema):
|
| 2945 |
+
dict_class = dict_cls
|
| 2946 |
+
foo = fields.String()
|
| 2947 |
+
|
| 2948 |
+
result = MySchema().dump({"foo": "bar"})
|
| 2949 |
+
assert result == {"foo": "bar"}
|
| 2950 |
+
assert isinstance(result, dict_cls)
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_serialization.py
ADDED
|
@@ -0,0 +1,1041 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for field serialization."""
|
| 2 |
+
|
| 3 |
+
import datetime as dt
|
| 4 |
+
import decimal
|
| 5 |
+
import ipaddress
|
| 6 |
+
import itertools
|
| 7 |
+
import math
|
| 8 |
+
import uuid
|
| 9 |
+
from collections import OrderedDict, namedtuple
|
| 10 |
+
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
from marshmallow import Schema, fields
|
| 14 |
+
from marshmallow import missing as missing_
|
| 15 |
+
from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class DateTimeList:
|
| 19 |
+
def __init__(self, dtimes):
|
| 20 |
+
self.dtimes = dtimes
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class IntegerList:
|
| 24 |
+
def __init__(self, ints):
|
| 25 |
+
self.ints = ints
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DateTimeIntegerTuple:
|
| 29 |
+
def __init__(self, dtime_int):
|
| 30 |
+
self.dtime_int = dtime_int
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestFieldSerialization:
|
| 34 |
+
@pytest.fixture
|
| 35 |
+
def user(self):
|
| 36 |
+
return User("Foo", email="foo@bar.com", age=42)
|
| 37 |
+
|
| 38 |
+
@pytest.mark.parametrize(
|
| 39 |
+
("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)]
|
| 40 |
+
)
|
| 41 |
+
def test_number(self, value, expected, user):
|
| 42 |
+
field = fields.Number()
|
| 43 |
+
user.age = value
|
| 44 |
+
assert field.serialize("age", user) == expected
|
| 45 |
+
|
| 46 |
+
def test_number_as_string(self, user):
|
| 47 |
+
user.age = 42
|
| 48 |
+
field = fields.Number(as_string=True)
|
| 49 |
+
assert field.serialize("age", user) == str(float(user.age))
|
| 50 |
+
|
| 51 |
+
def test_number_as_string_passed_none(self, user):
|
| 52 |
+
user.age = None
|
| 53 |
+
field = fields.Number(as_string=True, allow_none=True)
|
| 54 |
+
assert field.serialize("age", user) is None
|
| 55 |
+
|
| 56 |
+
def test_function_field_passed_func(self, user):
|
| 57 |
+
field = fields.Function(lambda obj: obj.name.upper())
|
| 58 |
+
assert "FOO" == field.serialize("key", user)
|
| 59 |
+
|
| 60 |
+
def test_function_field_passed_serialize_only_is_dump_only(self, user):
|
| 61 |
+
field = fields.Function(serialize=lambda obj: obj.name.upper())
|
| 62 |
+
assert field.dump_only is True
|
| 63 |
+
|
| 64 |
+
def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self):
|
| 65 |
+
field = fields.Function(
|
| 66 |
+
serialize=lambda val: val.lower(), deserialize=lambda val: val.upper()
|
| 67 |
+
)
|
| 68 |
+
assert field.dump_only is False
|
| 69 |
+
|
| 70 |
+
def test_function_field_passed_serialize(self, user):
|
| 71 |
+
field = fields.Function(serialize=lambda obj: obj.name.upper())
|
| 72 |
+
assert "FOO" == field.serialize("key", user)
|
| 73 |
+
|
| 74 |
+
# https://github.com/marshmallow-code/marshmallow/issues/395
|
| 75 |
+
def test_function_field_does_not_swallow_attribute_error(self, user):
|
| 76 |
+
def raise_error(obj):
|
| 77 |
+
raise AttributeError()
|
| 78 |
+
|
| 79 |
+
field = fields.Function(serialize=raise_error)
|
| 80 |
+
with pytest.raises(AttributeError):
|
| 81 |
+
field.serialize("key", user)
|
| 82 |
+
|
| 83 |
+
def test_serialize_with_load_only_param(self):
|
| 84 |
+
class AliasingUserSerializer(Schema):
|
| 85 |
+
name = fields.String()
|
| 86 |
+
years = fields.Integer(load_only=True)
|
| 87 |
+
size = fields.Integer(dump_only=True, load_only=True)
|
| 88 |
+
nicknames = fields.List(fields.Str(), load_only=True)
|
| 89 |
+
|
| 90 |
+
data = {
|
| 91 |
+
"name": "Mick",
|
| 92 |
+
"years": "42",
|
| 93 |
+
"size": "12",
|
| 94 |
+
"nicknames": ["Your Majesty", "Brenda"],
|
| 95 |
+
}
|
| 96 |
+
result = AliasingUserSerializer().dump(data)
|
| 97 |
+
assert result["name"] == "Mick"
|
| 98 |
+
assert "years" not in result
|
| 99 |
+
assert "size" not in result
|
| 100 |
+
assert "nicknames" not in result
|
| 101 |
+
|
| 102 |
+
def test_function_field_load_only(self):
|
| 103 |
+
field = fields.Function(deserialize=lambda obj: None)
|
| 104 |
+
assert field.load_only
|
| 105 |
+
|
| 106 |
+
def test_function_field_passed_serialize_with_context(self, user, monkeypatch):
|
| 107 |
+
class Parent(Schema):
|
| 108 |
+
pass
|
| 109 |
+
|
| 110 |
+
field = fields.Function(
|
| 111 |
+
serialize=lambda obj, context: obj.name.upper() + context["key"]
|
| 112 |
+
)
|
| 113 |
+
field.parent = Parent(context={"key": "BAR"})
|
| 114 |
+
assert "FOOBAR" == field.serialize("key", user)
|
| 115 |
+
|
| 116 |
+
def test_function_field_passed_uncallable_object(self):
|
| 117 |
+
with pytest.raises(TypeError):
|
| 118 |
+
fields.Function("uncallable")
|
| 119 |
+
|
| 120 |
+
def test_integer_field(self, user):
|
| 121 |
+
field = fields.Integer()
|
| 122 |
+
assert field.serialize("age", user) == 42
|
| 123 |
+
|
| 124 |
+
def test_integer_as_string_field(self, user):
|
| 125 |
+
field = fields.Integer(as_string=True)
|
| 126 |
+
assert field.serialize("age", user) == "42"
|
| 127 |
+
|
| 128 |
+
def test_integer_field_default(self, user):
|
| 129 |
+
user.age = None
|
| 130 |
+
field = fields.Integer(dump_default=0)
|
| 131 |
+
assert field.serialize("age", user) is None
|
| 132 |
+
# missing
|
| 133 |
+
assert field.serialize("age", {}) == 0
|
| 134 |
+
|
| 135 |
+
def test_integer_field_default_set_to_none(self, user):
|
| 136 |
+
user.age = None
|
| 137 |
+
field = fields.Integer(dump_default=None)
|
| 138 |
+
assert field.serialize("age", user) is None
|
| 139 |
+
|
| 140 |
+
def test_uuid_field(self, user):
|
| 141 |
+
user.uuid1 = uuid.UUID("12345678123456781234567812345678")
|
| 142 |
+
user.uuid2 = None
|
| 143 |
+
|
| 144 |
+
field = fields.UUID()
|
| 145 |
+
assert isinstance(field.serialize("uuid1", user), str)
|
| 146 |
+
assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678"
|
| 147 |
+
assert field.serialize("uuid2", user) is None
|
| 148 |
+
|
| 149 |
+
def test_ip_address_field(self, user):
|
| 150 |
+
ipv4_string = "192.168.0.1"
|
| 151 |
+
ipv6_string = "ffff::ffff"
|
| 152 |
+
ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded
|
| 153 |
+
|
| 154 |
+
user.ipv4 = ipaddress.ip_address(ipv4_string)
|
| 155 |
+
user.ipv6 = ipaddress.ip_address(ipv6_string)
|
| 156 |
+
user.empty_ip = None
|
| 157 |
+
|
| 158 |
+
field_compressed = fields.IP()
|
| 159 |
+
assert isinstance(field_compressed.serialize("ipv4", user), str)
|
| 160 |
+
assert field_compressed.serialize("ipv4", user) == ipv4_string
|
| 161 |
+
assert isinstance(field_compressed.serialize("ipv6", user), str)
|
| 162 |
+
assert field_compressed.serialize("ipv6", user) == ipv6_string
|
| 163 |
+
assert field_compressed.serialize("empty_ip", user) is None
|
| 164 |
+
|
| 165 |
+
field_exploded = fields.IP(exploded=True)
|
| 166 |
+
assert isinstance(field_exploded.serialize("ipv6", user), str)
|
| 167 |
+
assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string
|
| 168 |
+
|
| 169 |
+
def test_ipv4_address_field(self, user):
|
| 170 |
+
ipv4_string = "192.168.0.1"
|
| 171 |
+
|
| 172 |
+
user.ipv4 = ipaddress.ip_address(ipv4_string)
|
| 173 |
+
user.empty_ip = None
|
| 174 |
+
|
| 175 |
+
field = fields.IPv4()
|
| 176 |
+
assert isinstance(field.serialize("ipv4", user), str)
|
| 177 |
+
assert field.serialize("ipv4", user) == ipv4_string
|
| 178 |
+
assert field.serialize("empty_ip", user) is None
|
| 179 |
+
|
| 180 |
+
def test_ipv6_address_field(self, user):
|
| 181 |
+
ipv6_string = "ffff::ffff"
|
| 182 |
+
ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded
|
| 183 |
+
|
| 184 |
+
user.ipv6 = ipaddress.ip_address(ipv6_string)
|
| 185 |
+
user.empty_ip = None
|
| 186 |
+
|
| 187 |
+
field_compressed = fields.IPv6()
|
| 188 |
+
assert isinstance(field_compressed.serialize("ipv6", user), str)
|
| 189 |
+
assert field_compressed.serialize("ipv6", user) == ipv6_string
|
| 190 |
+
assert field_compressed.serialize("empty_ip", user) is None
|
| 191 |
+
|
| 192 |
+
field_exploded = fields.IPv6(exploded=True)
|
| 193 |
+
assert isinstance(field_exploded.serialize("ipv6", user), str)
|
| 194 |
+
assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string
|
| 195 |
+
|
| 196 |
+
def test_ip_interface_field(self, user):
|
| 197 |
+
ipv4interface_string = "192.168.0.1/24"
|
| 198 |
+
ipv6interface_string = "ffff::ffff/128"
|
| 199 |
+
ipv6interface_exploded_string = ipaddress.ip_interface(
|
| 200 |
+
"ffff::ffff/128"
|
| 201 |
+
).exploded
|
| 202 |
+
|
| 203 |
+
user.ipv4interface = ipaddress.ip_interface(ipv4interface_string)
|
| 204 |
+
user.ipv6interface = ipaddress.ip_interface(ipv6interface_string)
|
| 205 |
+
user.empty_ipinterface = None
|
| 206 |
+
|
| 207 |
+
field_compressed = fields.IPInterface()
|
| 208 |
+
assert isinstance(field_compressed.serialize("ipv4interface", user), str)
|
| 209 |
+
assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string
|
| 210 |
+
assert isinstance(field_compressed.serialize("ipv6interface", user), str)
|
| 211 |
+
assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string
|
| 212 |
+
assert field_compressed.serialize("empty_ipinterface", user) is None
|
| 213 |
+
|
| 214 |
+
field_exploded = fields.IPInterface(exploded=True)
|
| 215 |
+
assert isinstance(field_exploded.serialize("ipv6interface", user), str)
|
| 216 |
+
assert (
|
| 217 |
+
field_exploded.serialize("ipv6interface", user)
|
| 218 |
+
== ipv6interface_exploded_string
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
def test_ipv4_interface_field(self, user):
|
| 222 |
+
ipv4interface_string = "192.168.0.1/24"
|
| 223 |
+
|
| 224 |
+
user.ipv4interface = ipaddress.ip_interface(ipv4interface_string)
|
| 225 |
+
user.empty_ipinterface = None
|
| 226 |
+
|
| 227 |
+
field = fields.IPv4Interface()
|
| 228 |
+
assert isinstance(field.serialize("ipv4interface", user), str)
|
| 229 |
+
assert field.serialize("ipv4interface", user) == ipv4interface_string
|
| 230 |
+
assert field.serialize("empty_ipinterface", user) is None
|
| 231 |
+
|
| 232 |
+
def test_ipv6_interface_field(self, user):
|
| 233 |
+
ipv6interface_string = "ffff::ffff/128"
|
| 234 |
+
ipv6interface_exploded_string = ipaddress.ip_interface(
|
| 235 |
+
"ffff::ffff/128"
|
| 236 |
+
).exploded
|
| 237 |
+
|
| 238 |
+
user.ipv6interface = ipaddress.ip_interface(ipv6interface_string)
|
| 239 |
+
user.empty_ipinterface = None
|
| 240 |
+
|
| 241 |
+
field_compressed = fields.IPv6Interface()
|
| 242 |
+
assert isinstance(field_compressed.serialize("ipv6interface", user), str)
|
| 243 |
+
assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string
|
| 244 |
+
assert field_compressed.serialize("empty_ipinterface", user) is None
|
| 245 |
+
|
| 246 |
+
field_exploded = fields.IPv6Interface(exploded=True)
|
| 247 |
+
assert isinstance(field_exploded.serialize("ipv6interface", user), str)
|
| 248 |
+
assert (
|
| 249 |
+
field_exploded.serialize("ipv6interface", user)
|
| 250 |
+
== ipv6interface_exploded_string
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
def test_enum_field_by_symbol_serialization(self, user):
|
| 254 |
+
user.sex = GenderEnum.male
|
| 255 |
+
field = fields.Enum(GenderEnum)
|
| 256 |
+
assert field.serialize("sex", user) == "male"
|
| 257 |
+
|
| 258 |
+
def test_enum_field_by_value_true_serialization(self, user):
|
| 259 |
+
user.hair_color = HairColorEnum.black
|
| 260 |
+
field = fields.Enum(HairColorEnum, by_value=True)
|
| 261 |
+
assert field.serialize("hair_color", user) == "black hair"
|
| 262 |
+
user.sex = GenderEnum.male
|
| 263 |
+
field = fields.Enum(GenderEnum, by_value=True)
|
| 264 |
+
assert field.serialize("sex", user) == 1
|
| 265 |
+
user.some_date = DateEnum.date_1
|
| 266 |
+
|
| 267 |
+
def test_enum_field_by_value_field_serialization(self, user):
|
| 268 |
+
user.hair_color = HairColorEnum.black
|
| 269 |
+
field = fields.Enum(HairColorEnum, by_value=fields.String)
|
| 270 |
+
assert field.serialize("hair_color", user) == "black hair"
|
| 271 |
+
user.sex = GenderEnum.male
|
| 272 |
+
field = fields.Enum(GenderEnum, by_value=fields.Integer)
|
| 273 |
+
assert field.serialize("sex", user) == 1
|
| 274 |
+
user.some_date = DateEnum.date_1
|
| 275 |
+
field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y"))
|
| 276 |
+
assert field.serialize("some_date", user) == "29/02/2004"
|
| 277 |
+
|
| 278 |
+
def test_decimal_field(self, user):
|
| 279 |
+
user.m1 = 12
|
| 280 |
+
user.m2 = "12.355"
|
| 281 |
+
user.m3 = decimal.Decimal(1)
|
| 282 |
+
user.m4 = None
|
| 283 |
+
|
| 284 |
+
field = fields.Decimal()
|
| 285 |
+
assert isinstance(field.serialize("m1", user), decimal.Decimal)
|
| 286 |
+
assert field.serialize("m1", user) == decimal.Decimal(12)
|
| 287 |
+
assert isinstance(field.serialize("m2", user), decimal.Decimal)
|
| 288 |
+
assert field.serialize("m2", user) == decimal.Decimal("12.355")
|
| 289 |
+
assert isinstance(field.serialize("m3", user), decimal.Decimal)
|
| 290 |
+
assert field.serialize("m3", user) == decimal.Decimal(1)
|
| 291 |
+
assert field.serialize("m4", user) is None
|
| 292 |
+
|
| 293 |
+
field = fields.Decimal(1)
|
| 294 |
+
assert isinstance(field.serialize("m1", user), decimal.Decimal)
|
| 295 |
+
assert field.serialize("m1", user) == decimal.Decimal(12)
|
| 296 |
+
assert isinstance(field.serialize("m2", user), decimal.Decimal)
|
| 297 |
+
assert field.serialize("m2", user) == decimal.Decimal("12.4")
|
| 298 |
+
assert isinstance(field.serialize("m3", user), decimal.Decimal)
|
| 299 |
+
assert field.serialize("m3", user) == decimal.Decimal(1)
|
| 300 |
+
assert field.serialize("m4", user) is None
|
| 301 |
+
|
| 302 |
+
field = fields.Decimal(1, decimal.ROUND_DOWN)
|
| 303 |
+
assert isinstance(field.serialize("m1", user), decimal.Decimal)
|
| 304 |
+
assert field.serialize("m1", user) == decimal.Decimal(12)
|
| 305 |
+
assert isinstance(field.serialize("m2", user), decimal.Decimal)
|
| 306 |
+
assert field.serialize("m2", user) == decimal.Decimal("12.3")
|
| 307 |
+
assert isinstance(field.serialize("m3", user), decimal.Decimal)
|
| 308 |
+
assert field.serialize("m3", user) == decimal.Decimal(1)
|
| 309 |
+
assert field.serialize("m4", user) is None
|
| 310 |
+
|
| 311 |
+
def test_decimal_field_string(self, user):
|
| 312 |
+
user.m1 = 12
|
| 313 |
+
user.m2 = "12.355"
|
| 314 |
+
user.m3 = decimal.Decimal(1)
|
| 315 |
+
user.m4 = None
|
| 316 |
+
|
| 317 |
+
field = fields.Decimal(as_string=True)
|
| 318 |
+
assert isinstance(field.serialize("m1", user), str)
|
| 319 |
+
assert field.serialize("m1", user) == "12"
|
| 320 |
+
assert isinstance(field.serialize("m2", user), str)
|
| 321 |
+
assert field.serialize("m2", user) == "12.355"
|
| 322 |
+
assert isinstance(field.serialize("m3", user), str)
|
| 323 |
+
assert field.serialize("m3", user) == "1"
|
| 324 |
+
assert field.serialize("m4", user) is None
|
| 325 |
+
|
| 326 |
+
field = fields.Decimal(1, as_string=True)
|
| 327 |
+
assert isinstance(field.serialize("m1", user), str)
|
| 328 |
+
assert field.serialize("m1", user) == "12.0"
|
| 329 |
+
assert isinstance(field.serialize("m2", user), str)
|
| 330 |
+
assert field.serialize("m2", user) == "12.4"
|
| 331 |
+
assert isinstance(field.serialize("m3", user), str)
|
| 332 |
+
assert field.serialize("m3", user) == "1.0"
|
| 333 |
+
assert field.serialize("m4", user) is None
|
| 334 |
+
|
| 335 |
+
field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True)
|
| 336 |
+
assert isinstance(field.serialize("m1", user), str)
|
| 337 |
+
assert field.serialize("m1", user) == "12.0"
|
| 338 |
+
assert isinstance(field.serialize("m2", user), str)
|
| 339 |
+
assert field.serialize("m2", user) == "12.3"
|
| 340 |
+
assert isinstance(field.serialize("m3", user), str)
|
| 341 |
+
assert field.serialize("m3", user) == "1.0"
|
| 342 |
+
assert field.serialize("m4", user) is None
|
| 343 |
+
|
| 344 |
+
def test_decimal_field_special_values(self, user):
|
| 345 |
+
user.m1 = "-NaN"
|
| 346 |
+
user.m2 = "NaN"
|
| 347 |
+
user.m3 = "-sNaN"
|
| 348 |
+
user.m4 = "sNaN"
|
| 349 |
+
user.m5 = "-Infinity"
|
| 350 |
+
user.m6 = "Infinity"
|
| 351 |
+
user.m7 = "-0"
|
| 352 |
+
|
| 353 |
+
field = fields.Decimal(places=2, allow_nan=True)
|
| 354 |
+
|
| 355 |
+
m1s = field.serialize("m1", user)
|
| 356 |
+
assert isinstance(m1s, decimal.Decimal)
|
| 357 |
+
assert m1s.is_qnan() and not m1s.is_signed()
|
| 358 |
+
|
| 359 |
+
m2s = field.serialize("m2", user)
|
| 360 |
+
assert isinstance(m2s, decimal.Decimal)
|
| 361 |
+
assert m2s.is_qnan() and not m2s.is_signed()
|
| 362 |
+
|
| 363 |
+
m3s = field.serialize("m3", user)
|
| 364 |
+
assert isinstance(m3s, decimal.Decimal)
|
| 365 |
+
assert m3s.is_qnan() and not m3s.is_signed()
|
| 366 |
+
|
| 367 |
+
m4s = field.serialize("m4", user)
|
| 368 |
+
assert isinstance(m4s, decimal.Decimal)
|
| 369 |
+
assert m4s.is_qnan() and not m4s.is_signed()
|
| 370 |
+
|
| 371 |
+
m5s = field.serialize("m5", user)
|
| 372 |
+
assert isinstance(m5s, decimal.Decimal)
|
| 373 |
+
assert m5s.is_infinite() and m5s.is_signed()
|
| 374 |
+
|
| 375 |
+
m6s = field.serialize("m6", user)
|
| 376 |
+
assert isinstance(m6s, decimal.Decimal)
|
| 377 |
+
assert m6s.is_infinite() and not m6s.is_signed()
|
| 378 |
+
|
| 379 |
+
m7s = field.serialize("m7", user)
|
| 380 |
+
assert isinstance(m7s, decimal.Decimal)
|
| 381 |
+
assert m7s.is_zero() and m7s.is_signed()
|
| 382 |
+
|
| 383 |
+
field = fields.Decimal(as_string=True, allow_nan=True)
|
| 384 |
+
|
| 385 |
+
m2s = field.serialize("m2", user)
|
| 386 |
+
assert isinstance(m2s, str)
|
| 387 |
+
assert m2s == user.m2
|
| 388 |
+
|
| 389 |
+
m5s = field.serialize("m5", user)
|
| 390 |
+
assert isinstance(m5s, str)
|
| 391 |
+
assert m5s == user.m5
|
| 392 |
+
|
| 393 |
+
m6s = field.serialize("m6", user)
|
| 394 |
+
assert isinstance(m6s, str)
|
| 395 |
+
assert m6s == user.m6
|
| 396 |
+
|
| 397 |
+
def test_decimal_field_special_values_not_permitted(self, user):
|
| 398 |
+
user.m7 = "-0"
|
| 399 |
+
|
| 400 |
+
field = fields.Decimal(places=2)
|
| 401 |
+
|
| 402 |
+
m7s = field.serialize("m7", user)
|
| 403 |
+
assert isinstance(m7s, decimal.Decimal)
|
| 404 |
+
assert m7s.is_zero() and m7s.is_signed()
|
| 405 |
+
|
| 406 |
+
def test_decimal_field_fixed_point_representation(self, user):
|
| 407 |
+
"""
|
| 408 |
+
Test we get fixed-point string representation for a Decimal number that would normally
|
| 409 |
+
output in engineering notation.
|
| 410 |
+
"""
|
| 411 |
+
user.m1 = "0.00000000100000000"
|
| 412 |
+
|
| 413 |
+
field = fields.Decimal()
|
| 414 |
+
s = field.serialize("m1", user)
|
| 415 |
+
assert isinstance(s, decimal.Decimal)
|
| 416 |
+
assert s == decimal.Decimal("1.00000000E-9")
|
| 417 |
+
|
| 418 |
+
field = fields.Decimal(as_string=True)
|
| 419 |
+
s = field.serialize("m1", user)
|
| 420 |
+
assert isinstance(s, str)
|
| 421 |
+
assert s == user.m1
|
| 422 |
+
|
| 423 |
+
field = fields.Decimal(as_string=True, places=2)
|
| 424 |
+
s = field.serialize("m1", user)
|
| 425 |
+
assert isinstance(s, str)
|
| 426 |
+
assert s == "0.00"
|
| 427 |
+
|
| 428 |
+
def test_boolean_field_serialization(self, user):
|
| 429 |
+
field = fields.Boolean()
|
| 430 |
+
|
| 431 |
+
user.truthy = "non-falsy-ish"
|
| 432 |
+
user.falsy = "false"
|
| 433 |
+
user.none = None
|
| 434 |
+
|
| 435 |
+
assert field.serialize("truthy", user) is True
|
| 436 |
+
assert field.serialize("falsy", user) is False
|
| 437 |
+
assert field.serialize("none", user) is None
|
| 438 |
+
|
| 439 |
+
def test_email_field_serialize_none(self, user):
|
| 440 |
+
user.email = None
|
| 441 |
+
field = fields.Email()
|
| 442 |
+
assert field.serialize("email", user) is None
|
| 443 |
+
|
| 444 |
+
def test_dict_field_serialize_none(self, user):
|
| 445 |
+
user.various_data = None
|
| 446 |
+
field = fields.Dict()
|
| 447 |
+
assert field.serialize("various_data", user) is None
|
| 448 |
+
|
| 449 |
+
def test_dict_field_serialize(self, user):
|
| 450 |
+
user.various_data = {"foo": "bar"}
|
| 451 |
+
field = fields.Dict()
|
| 452 |
+
dump = field.serialize("various_data", user)
|
| 453 |
+
assert dump == {"foo": "bar"}
|
| 454 |
+
# Check dump is a distinct object
|
| 455 |
+
dump["foo"] = "baz"
|
| 456 |
+
assert user.various_data["foo"] == "bar"
|
| 457 |
+
|
| 458 |
+
def test_dict_field_serialize_ordereddict(self, user):
|
| 459 |
+
user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")])
|
| 460 |
+
field = fields.Dict()
|
| 461 |
+
assert field.serialize("various_data", user) == OrderedDict(
|
| 462 |
+
[("foo", "bar"), ("bar", "baz")]
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
def test_structured_dict_value_serialize(self, user):
|
| 466 |
+
user.various_data = {"foo": decimal.Decimal("1")}
|
| 467 |
+
field = fields.Dict(values=fields.Decimal)
|
| 468 |
+
assert field.serialize("various_data", user) == {"foo": 1}
|
| 469 |
+
|
| 470 |
+
def test_structured_dict_key_serialize(self, user):
|
| 471 |
+
user.various_data = {1: "bar"}
|
| 472 |
+
field = fields.Dict(keys=fields.Str)
|
| 473 |
+
assert field.serialize("various_data", user) == {"1": "bar"}
|
| 474 |
+
|
| 475 |
+
def test_structured_dict_key_value_serialize(self, user):
|
| 476 |
+
user.various_data = {1: decimal.Decimal("1")}
|
| 477 |
+
field = fields.Dict(keys=fields.Str, values=fields.Decimal)
|
| 478 |
+
assert field.serialize("various_data", user) == {"1": 1}
|
| 479 |
+
|
| 480 |
+
def test_url_field_serialize_none(self, user):
|
| 481 |
+
user.homepage = None
|
| 482 |
+
field = fields.Url()
|
| 483 |
+
assert field.serialize("homepage", user) is None
|
| 484 |
+
|
| 485 |
+
def test_method_field_with_method_missing(self):
|
| 486 |
+
class BadSerializer(Schema):
|
| 487 |
+
bad_field = fields.Method("invalid")
|
| 488 |
+
|
| 489 |
+
with pytest.raises(AttributeError):
|
| 490 |
+
BadSerializer()
|
| 491 |
+
|
| 492 |
+
def test_method_field_passed_serialize_only_is_dump_only(self, user):
|
| 493 |
+
field = fields.Method(serialize="method")
|
| 494 |
+
assert field.dump_only is True
|
| 495 |
+
assert field.load_only is False
|
| 496 |
+
|
| 497 |
+
def test_method_field_passed_deserialize_only_is_load_only(self):
|
| 498 |
+
field = fields.Method(deserialize="somemethod")
|
| 499 |
+
assert field.load_only is True
|
| 500 |
+
assert field.dump_only is False
|
| 501 |
+
|
| 502 |
+
def test_method_field_with_uncallable_attribute(self):
|
| 503 |
+
class BadSerializer(Schema):
|
| 504 |
+
foo = "not callable"
|
| 505 |
+
bad_field = fields.Method("foo")
|
| 506 |
+
|
| 507 |
+
with pytest.raises(TypeError):
|
| 508 |
+
BadSerializer()
|
| 509 |
+
|
| 510 |
+
# https://github.com/marshmallow-code/marshmallow/issues/395
|
| 511 |
+
def test_method_field_does_not_swallow_attribute_error(self):
|
| 512 |
+
class MySchema(Schema):
|
| 513 |
+
mfield = fields.Method("raise_error")
|
| 514 |
+
|
| 515 |
+
def raise_error(self, obj):
|
| 516 |
+
raise AttributeError()
|
| 517 |
+
|
| 518 |
+
with pytest.raises(AttributeError):
|
| 519 |
+
MySchema().dump({})
|
| 520 |
+
|
| 521 |
+
def test_method_with_no_serialize_is_missing(self):
|
| 522 |
+
m = fields.Method()
|
| 523 |
+
m.parent = Schema()
|
| 524 |
+
|
| 525 |
+
assert m.serialize("", "", "") is missing_
|
| 526 |
+
|
| 527 |
+
def test_serialize_with_data_key_param(self):
|
| 528 |
+
class DumpToSchema(Schema):
|
| 529 |
+
name = fields.String(data_key="NamE")
|
| 530 |
+
years = fields.Integer(data_key="YearS")
|
| 531 |
+
|
| 532 |
+
data = {"name": "Richard", "years": 11}
|
| 533 |
+
result = DumpToSchema().dump(data)
|
| 534 |
+
assert result == {"NamE": "Richard", "YearS": 11}
|
| 535 |
+
|
| 536 |
+
def test_serialize_with_data_key_as_empty_string(self):
|
| 537 |
+
class MySchema(Schema):
|
| 538 |
+
name = fields.Field(data_key="")
|
| 539 |
+
|
| 540 |
+
schema = MySchema()
|
| 541 |
+
assert schema.dump({"name": "Grace"}) == {"": "Grace"}
|
| 542 |
+
|
| 543 |
+
def test_serialize_with_attribute_and_data_key_uses_data_key(self):
|
| 544 |
+
class ConfusedDumpToAndAttributeSerializer(Schema):
|
| 545 |
+
name = fields.String(data_key="FullName")
|
| 546 |
+
username = fields.String(attribute="uname", data_key="UserName")
|
| 547 |
+
years = fields.Integer(attribute="le_wild_age", data_key="Years")
|
| 548 |
+
|
| 549 |
+
data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999}
|
| 550 |
+
result = ConfusedDumpToAndAttributeSerializer().dump(data)
|
| 551 |
+
|
| 552 |
+
assert result == {
|
| 553 |
+
"FullName": "Mick",
|
| 554 |
+
"UserName": "mick_the_awesome",
|
| 555 |
+
"Years": 999,
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
@pytest.mark.parametrize("fmt", ["rfc", "rfc822"])
|
| 559 |
+
@pytest.mark.parametrize(
|
| 560 |
+
("value", "expected"),
|
| 561 |
+
[
|
| 562 |
+
(dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"),
|
| 563 |
+
(
|
| 564 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
|
| 565 |
+
"Sun, 10 Nov 2013 01:23:45 +0000",
|
| 566 |
+
),
|
| 567 |
+
(
|
| 568 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central),
|
| 569 |
+
"Sun, 10 Nov 2013 01:23:45 -0600",
|
| 570 |
+
),
|
| 571 |
+
],
|
| 572 |
+
)
|
| 573 |
+
def test_datetime_field_rfc822(self, fmt, value, expected):
|
| 574 |
+
field = fields.DateTime(format=fmt)
|
| 575 |
+
assert field.serialize("d", {"d": value}) == expected
|
| 576 |
+
|
| 577 |
+
@pytest.mark.parametrize(
|
| 578 |
+
("fmt", "value", "expected"),
|
| 579 |
+
[
|
| 580 |
+
("timestamp", dt.datetime(1970, 1, 1), 0),
|
| 581 |
+
("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025),
|
| 582 |
+
(
|
| 583 |
+
"timestamp",
|
| 584 |
+
dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc),
|
| 585 |
+
1384043025,
|
| 586 |
+
),
|
| 587 |
+
(
|
| 588 |
+
"timestamp",
|
| 589 |
+
dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central),
|
| 590 |
+
1384064625,
|
| 591 |
+
),
|
| 592 |
+
("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000),
|
| 593 |
+
(
|
| 594 |
+
"timestamp_ms",
|
| 595 |
+
dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc),
|
| 596 |
+
1384043025000,
|
| 597 |
+
),
|
| 598 |
+
(
|
| 599 |
+
"timestamp_ms",
|
| 600 |
+
dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central),
|
| 601 |
+
1384064625000,
|
| 602 |
+
),
|
| 603 |
+
],
|
| 604 |
+
)
|
| 605 |
+
def test_datetime_field_timestamp(self, fmt, value, expected):
|
| 606 |
+
field = fields.DateTime(format=fmt)
|
| 607 |
+
assert field.serialize("d", {"d": value}) == expected
|
| 608 |
+
|
| 609 |
+
@pytest.mark.parametrize("fmt", ["iso", "iso8601", None])
|
| 610 |
+
@pytest.mark.parametrize(
|
| 611 |
+
("value", "expected"),
|
| 612 |
+
[
|
| 613 |
+
(dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"),
|
| 614 |
+
(
|
| 615 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc),
|
| 616 |
+
"2013-11-10T01:23:45.123456+00:00",
|
| 617 |
+
),
|
| 618 |
+
(
|
| 619 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
|
| 620 |
+
"2013-11-10T01:23:45+00:00",
|
| 621 |
+
),
|
| 622 |
+
(
|
| 623 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central),
|
| 624 |
+
"2013-11-10T01:23:45-06:00",
|
| 625 |
+
),
|
| 626 |
+
],
|
| 627 |
+
)
|
| 628 |
+
def test_datetime_field_iso8601(self, fmt, value, expected):
|
| 629 |
+
if fmt is None:
|
| 630 |
+
# Test default is ISO
|
| 631 |
+
field = fields.DateTime()
|
| 632 |
+
else:
|
| 633 |
+
field = fields.DateTime(format=fmt)
|
| 634 |
+
assert field.serialize("d", {"d": value}) == expected
|
| 635 |
+
|
| 636 |
+
def test_datetime_field_format(self, user):
|
| 637 |
+
format = "%Y-%m-%d"
|
| 638 |
+
field = fields.DateTime(format=format)
|
| 639 |
+
assert field.serialize("created", user) == user.created.strftime(format)
|
| 640 |
+
|
| 641 |
+
def test_string_field(self):
|
| 642 |
+
field = fields.String()
|
| 643 |
+
user = User(name=b"foo")
|
| 644 |
+
assert field.serialize("name", user) == "foo"
|
| 645 |
+
field = fields.String(allow_none=True)
|
| 646 |
+
user.name = None
|
| 647 |
+
assert field.serialize("name", user) is None
|
| 648 |
+
|
| 649 |
+
def test_string_field_default_to_empty_string(self, user):
|
| 650 |
+
field = fields.String(dump_default="")
|
| 651 |
+
assert field.serialize("notfound", {}) == ""
|
| 652 |
+
|
| 653 |
+
def test_time_field(self, user):
|
| 654 |
+
field = fields.Time()
|
| 655 |
+
expected = user.time_registered.isoformat()[:15]
|
| 656 |
+
assert field.serialize("time_registered", user) == expected
|
| 657 |
+
|
| 658 |
+
user.time_registered = None
|
| 659 |
+
assert field.serialize("time_registered", user) is None
|
| 660 |
+
|
| 661 |
+
@pytest.mark.parametrize("fmt", ["iso", "iso8601", None])
|
| 662 |
+
@pytest.mark.parametrize(
|
| 663 |
+
("value", "expected"),
|
| 664 |
+
[
|
| 665 |
+
(dt.time(1, 23, 45), "01:23:45"),
|
| 666 |
+
(dt.time(1, 23, 45, 123000), "01:23:45.123000"),
|
| 667 |
+
(dt.time(1, 23, 45, 123456), "01:23:45.123456"),
|
| 668 |
+
],
|
| 669 |
+
)
|
| 670 |
+
def test_time_field_iso8601(self, fmt, value, expected):
|
| 671 |
+
if fmt is None:
|
| 672 |
+
# Test default is ISO
|
| 673 |
+
field = fields.Time()
|
| 674 |
+
else:
|
| 675 |
+
field = fields.Time(format=fmt)
|
| 676 |
+
assert field.serialize("d", {"d": value}) == expected
|
| 677 |
+
|
| 678 |
+
def test_time_field_format(self, user):
|
| 679 |
+
fmt = "%H:%M:%S"
|
| 680 |
+
field = fields.Time(format=fmt)
|
| 681 |
+
assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt)
|
| 682 |
+
|
| 683 |
+
def test_date_field(self, user):
|
| 684 |
+
field = fields.Date()
|
| 685 |
+
assert field.serialize("birthdate", user) == user.birthdate.isoformat()
|
| 686 |
+
|
| 687 |
+
user.birthdate = None
|
| 688 |
+
assert field.serialize("birthdate", user) is None
|
| 689 |
+
|
| 690 |
+
def test_timedelta_field(self, user):
|
| 691 |
+
user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1)
|
| 692 |
+
user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1)
|
| 693 |
+
user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001)
|
| 694 |
+
user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0)
|
| 695 |
+
user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0)
|
| 696 |
+
user.d6 = dt.timedelta(
|
| 697 |
+
days=1,
|
| 698 |
+
seconds=1,
|
| 699 |
+
microseconds=1,
|
| 700 |
+
milliseconds=1,
|
| 701 |
+
minutes=1,
|
| 702 |
+
hours=1,
|
| 703 |
+
weeks=1,
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS)
|
| 707 |
+
assert field.serialize("d1", user) == 1
|
| 708 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS)
|
| 709 |
+
assert field.serialize("d1", user) == 86401
|
| 710 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
|
| 711 |
+
assert field.serialize("d1", user) == 86401000001
|
| 712 |
+
field = fields.TimeDelta(fields.TimeDelta.HOURS)
|
| 713 |
+
assert field.serialize("d1", user) == 24
|
| 714 |
+
|
| 715 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS)
|
| 716 |
+
assert field.serialize("d2", user) == 1
|
| 717 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS)
|
| 718 |
+
assert field.serialize("d2", user) == 86401
|
| 719 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
|
| 720 |
+
assert field.serialize("d2", user) == 86401000001
|
| 721 |
+
|
| 722 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS)
|
| 723 |
+
assert field.serialize("d3", user) == 1
|
| 724 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS)
|
| 725 |
+
assert field.serialize("d3", user) == 86401
|
| 726 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
|
| 727 |
+
assert field.serialize("d3", user) == 86401000001
|
| 728 |
+
|
| 729 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS)
|
| 730 |
+
assert field.serialize("d4", user) == 0
|
| 731 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS)
|
| 732 |
+
assert field.serialize("d4", user) == 0
|
| 733 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
|
| 734 |
+
assert field.serialize("d4", user) == 0
|
| 735 |
+
|
| 736 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS)
|
| 737 |
+
assert field.serialize("d5", user) == -1
|
| 738 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS)
|
| 739 |
+
assert field.serialize("d5", user) == -86400
|
| 740 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
|
| 741 |
+
assert field.serialize("d5", user) == -86400000000
|
| 742 |
+
|
| 743 |
+
field = fields.TimeDelta(fields.TimeDelta.WEEKS)
|
| 744 |
+
assert field.serialize("d6", user) == 1
|
| 745 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS)
|
| 746 |
+
assert field.serialize("d6", user) == 7 + 1
|
| 747 |
+
field = fields.TimeDelta(fields.TimeDelta.HOURS)
|
| 748 |
+
assert field.serialize("d6", user) == 7 * 24 + 24 + 1
|
| 749 |
+
field = fields.TimeDelta(fields.TimeDelta.MINUTES)
|
| 750 |
+
assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1
|
| 751 |
+
d6_seconds = (
|
| 752 |
+
7 * 24 * 60 * 60
|
| 753 |
+
+ 24 * 60 * 60 # 1 week
|
| 754 |
+
+ 60 * 60 # 1 day
|
| 755 |
+
+ 60 # 1 hour
|
| 756 |
+
+ 1 # 1 minute
|
| 757 |
+
)
|
| 758 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS)
|
| 759 |
+
assert field.serialize("d6", user) == d6_seconds
|
| 760 |
+
field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS)
|
| 761 |
+
assert field.serialize("d6", user) == d6_seconds * 1000 + 1
|
| 762 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
|
| 763 |
+
assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1
|
| 764 |
+
|
| 765 |
+
user.d7 = None
|
| 766 |
+
assert field.serialize("d7", user) is None
|
| 767 |
+
|
| 768 |
+
# https://github.com/marshmallow-code/marshmallow/issues/1856
|
| 769 |
+
user.d8 = dt.timedelta(milliseconds=345)
|
| 770 |
+
field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS)
|
| 771 |
+
assert field.serialize("d8", user) == 345
|
| 772 |
+
|
| 773 |
+
user.d9 = dt.timedelta(milliseconds=1999)
|
| 774 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS)
|
| 775 |
+
assert field.serialize("d9", user) == 1
|
| 776 |
+
|
| 777 |
+
user.d10 = dt.timedelta(
|
| 778 |
+
weeks=1,
|
| 779 |
+
days=6,
|
| 780 |
+
hours=2,
|
| 781 |
+
minutes=5,
|
| 782 |
+
seconds=51,
|
| 783 |
+
milliseconds=10,
|
| 784 |
+
microseconds=742,
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float)
|
| 788 |
+
unit_value = dt.timedelta(microseconds=1).total_seconds()
|
| 789 |
+
assert math.isclose(
|
| 790 |
+
field.serialize("d10", user), user.d10.total_seconds() / unit_value
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float)
|
| 794 |
+
unit_value = dt.timedelta(milliseconds=1).total_seconds()
|
| 795 |
+
assert math.isclose(
|
| 796 |
+
field.serialize("d10", user), user.d10.total_seconds() / unit_value
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS, float)
|
| 800 |
+
assert math.isclose(field.serialize("d10", user), user.d10.total_seconds())
|
| 801 |
+
|
| 802 |
+
field = fields.TimeDelta(fields.TimeDelta.MINUTES, float)
|
| 803 |
+
unit_value = dt.timedelta(minutes=1).total_seconds()
|
| 804 |
+
assert math.isclose(
|
| 805 |
+
field.serialize("d10", user), user.d10.total_seconds() / unit_value
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
field = fields.TimeDelta(fields.TimeDelta.HOURS, float)
|
| 809 |
+
unit_value = dt.timedelta(hours=1).total_seconds()
|
| 810 |
+
assert math.isclose(
|
| 811 |
+
field.serialize("d10", user), user.d10.total_seconds() / unit_value
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS, float)
|
| 815 |
+
unit_value = dt.timedelta(days=1).total_seconds()
|
| 816 |
+
assert math.isclose(
|
| 817 |
+
field.serialize("d10", user), user.d10.total_seconds() / unit_value
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
+
field = fields.TimeDelta(fields.TimeDelta.WEEKS, float)
|
| 821 |
+
unit_value = dt.timedelta(weeks=1).total_seconds()
|
| 822 |
+
assert math.isclose(
|
| 823 |
+
field.serialize("d10", user), user.d10.total_seconds() / unit_value
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
with pytest.raises(ValueError):
|
| 827 |
+
fields.TimeDelta(fields.TimeDelta.SECONDS, str)
|
| 828 |
+
|
| 829 |
+
def test_datetime_list_field(self):
|
| 830 |
+
obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()])
|
| 831 |
+
field = fields.List(fields.DateTime)
|
| 832 |
+
result = field.serialize("dtimes", obj)
|
| 833 |
+
assert all(type(each) is str for each in result)
|
| 834 |
+
|
| 835 |
+
def test_list_field_serialize_none_returns_none(self):
|
| 836 |
+
obj = DateTimeList(None)
|
| 837 |
+
field = fields.List(fields.DateTime)
|
| 838 |
+
assert field.serialize("dtimes", obj) is None
|
| 839 |
+
|
| 840 |
+
def test_list_field_work_with_generator_single_value(self):
|
| 841 |
+
def custom_generator():
|
| 842 |
+
yield dt.datetime.now(dt.timezone.utc)
|
| 843 |
+
|
| 844 |
+
obj = DateTimeList(custom_generator())
|
| 845 |
+
field = fields.List(fields.DateTime)
|
| 846 |
+
result = field.serialize("dtimes", obj)
|
| 847 |
+
assert len(result) == 1
|
| 848 |
+
|
| 849 |
+
def test_list_field_work_with_generators_multiple_values(self):
|
| 850 |
+
def custom_generator():
|
| 851 |
+
yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()]
|
| 852 |
+
|
| 853 |
+
obj = DateTimeList(custom_generator())
|
| 854 |
+
field = fields.List(fields.DateTime)
|
| 855 |
+
result = field.serialize("dtimes", obj)
|
| 856 |
+
assert len(result) == 2
|
| 857 |
+
|
| 858 |
+
def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950
|
| 859 |
+
self,
|
| 860 |
+
):
|
| 861 |
+
def custom_generator():
|
| 862 |
+
yield
|
| 863 |
+
yield
|
| 864 |
+
|
| 865 |
+
obj = DateTimeList(custom_generator())
|
| 866 |
+
field = fields.List(fields.DateTime, allow_none=True)
|
| 867 |
+
result = field.serialize("dtimes", obj)
|
| 868 |
+
assert len(result) == 2
|
| 869 |
+
assert result[0] is None
|
| 870 |
+
assert result[1] is None
|
| 871 |
+
|
| 872 |
+
def test_list_field_work_with_set(self):
|
| 873 |
+
custom_set = {1, 2, 3}
|
| 874 |
+
obj = IntegerList(custom_set)
|
| 875 |
+
field = fields.List(fields.Int)
|
| 876 |
+
result = field.serialize("ints", obj)
|
| 877 |
+
assert len(result) == 3
|
| 878 |
+
assert 1 in result
|
| 879 |
+
assert 2 in result
|
| 880 |
+
assert 3 in result
|
| 881 |
+
|
| 882 |
+
def test_list_field_work_with_custom_class_with_iterator_protocol(self):
|
| 883 |
+
class IteratorSupportingClass:
|
| 884 |
+
def __init__(self, iterable):
|
| 885 |
+
self.iterable = iterable
|
| 886 |
+
|
| 887 |
+
def __iter__(self):
|
| 888 |
+
return iter(self.iterable)
|
| 889 |
+
|
| 890 |
+
ints = IteratorSupportingClass([1, 2, 3])
|
| 891 |
+
obj = IntegerList(ints)
|
| 892 |
+
field = fields.List(fields.Int)
|
| 893 |
+
result = field.serialize("ints", obj)
|
| 894 |
+
assert len(result) == 3
|
| 895 |
+
assert result[0] == 1
|
| 896 |
+
assert result[1] == 2
|
| 897 |
+
assert result[2] == 3
|
| 898 |
+
|
| 899 |
+
def test_bad_list_field(self):
|
| 900 |
+
class ASchema(Schema):
|
| 901 |
+
id = fields.Int()
|
| 902 |
+
|
| 903 |
+
with pytest.raises(ValueError):
|
| 904 |
+
fields.List("string")
|
| 905 |
+
expected_msg = (
|
| 906 |
+
"The list elements must be a subclass or instance of "
|
| 907 |
+
"marshmallow.base.FieldABC"
|
| 908 |
+
)
|
| 909 |
+
with pytest.raises(ValueError, match=expected_msg):
|
| 910 |
+
fields.List(ASchema)
|
| 911 |
+
|
| 912 |
+
def test_datetime_integer_tuple_field(self):
|
| 913 |
+
obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42))
|
| 914 |
+
field = fields.Tuple([fields.DateTime, fields.Integer])
|
| 915 |
+
result = field.serialize("dtime_int", obj)
|
| 916 |
+
assert type(result[0]) is str
|
| 917 |
+
assert type(result[1]) is int
|
| 918 |
+
|
| 919 |
+
def test_tuple_field_serialize_none_returns_none(self):
|
| 920 |
+
obj = DateTimeIntegerTuple(None)
|
| 921 |
+
field = fields.Tuple([fields.DateTime, fields.Integer])
|
| 922 |
+
assert field.serialize("dtime_int", obj) is None
|
| 923 |
+
|
| 924 |
+
def test_bad_tuple_field(self):
|
| 925 |
+
class ASchema(Schema):
|
| 926 |
+
id = fields.Int()
|
| 927 |
+
|
| 928 |
+
with pytest.raises(ValueError):
|
| 929 |
+
fields.Tuple(["string"])
|
| 930 |
+
with pytest.raises(ValueError):
|
| 931 |
+
fields.Tuple(fields.String)
|
| 932 |
+
expected_msg = (
|
| 933 |
+
'Elements of "tuple_fields" must be subclasses or '
|
| 934 |
+
"instances of marshmallow.base.FieldABC."
|
| 935 |
+
)
|
| 936 |
+
with pytest.raises(ValueError, match=expected_msg):
|
| 937 |
+
fields.Tuple([ASchema])
|
| 938 |
+
|
| 939 |
+
def test_serialize_does_not_apply_validators(self, user):
|
| 940 |
+
field = fields.Field(validate=lambda x: False)
|
| 941 |
+
# No validation error raised
|
| 942 |
+
assert field.serialize("age", user) == user.age
|
| 943 |
+
|
| 944 |
+
def test_constant_field_serialization(self, user):
|
| 945 |
+
field = fields.Constant("something")
|
| 946 |
+
assert field.serialize("whatever", user) == "something"
|
| 947 |
+
|
| 948 |
+
def test_constant_is_always_included_in_serialized_data(self):
|
| 949 |
+
class MySchema(Schema):
|
| 950 |
+
foo = fields.Constant(42)
|
| 951 |
+
|
| 952 |
+
sch = MySchema()
|
| 953 |
+
assert sch.dump({"bar": 24})["foo"] == 42
|
| 954 |
+
assert sch.dump({"foo": 24})["foo"] == 42
|
| 955 |
+
|
| 956 |
+
def test_constant_field_serialize_when_omitted(self):
|
| 957 |
+
class MiniUserSchema(Schema):
|
| 958 |
+
name = fields.Constant("bill")
|
| 959 |
+
|
| 960 |
+
s = MiniUserSchema()
|
| 961 |
+
assert s.dump({})["name"] == "bill"
|
| 962 |
+
|
| 963 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 964 |
+
def test_all_fields_serialize_none_to_none(self, FieldClass):
|
| 965 |
+
field = FieldClass(allow_none=True)
|
| 966 |
+
res = field.serialize("foo", {"foo": None})
|
| 967 |
+
assert res is None
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
class TestSchemaSerialization:
|
| 971 |
+
def test_serialize_with_missing_param_value(self):
|
| 972 |
+
class AliasingUserSerializer(Schema):
|
| 973 |
+
name = fields.String()
|
| 974 |
+
birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29))
|
| 975 |
+
|
| 976 |
+
data = {"name": "Mick"}
|
| 977 |
+
result = AliasingUserSerializer().dump(data)
|
| 978 |
+
assert result["name"] == "Mick"
|
| 979 |
+
assert result["birthdate"] == "2017-09-29T00:00:00"
|
| 980 |
+
|
| 981 |
+
def test_serialize_with_missing_param_callable(self):
|
| 982 |
+
class AliasingUserSerializer(Schema):
|
| 983 |
+
name = fields.String()
|
| 984 |
+
birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29))
|
| 985 |
+
|
| 986 |
+
data = {"name": "Mick"}
|
| 987 |
+
result = AliasingUserSerializer().dump(data)
|
| 988 |
+
assert result["name"] == "Mick"
|
| 989 |
+
assert result["birthdate"] == "2017-09-29T00:00:00"
|
| 990 |
+
|
| 991 |
+
|
| 992 |
+
def test_serializing_named_tuple():
|
| 993 |
+
Point = namedtuple("Point", ["x", "y"])
|
| 994 |
+
|
| 995 |
+
field = fields.Field()
|
| 996 |
+
|
| 997 |
+
p = Point(x=4, y=2)
|
| 998 |
+
|
| 999 |
+
assert field.serialize("x", p) == 4
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
def test_serializing_named_tuple_with_meta():
|
| 1003 |
+
Point = namedtuple("Point", ["x", "y"])
|
| 1004 |
+
p = Point(x=4, y=2)
|
| 1005 |
+
|
| 1006 |
+
class PointSerializer(Schema):
|
| 1007 |
+
class Meta:
|
| 1008 |
+
fields = ("x", "y")
|
| 1009 |
+
|
| 1010 |
+
serialized = PointSerializer().dump(p)
|
| 1011 |
+
assert serialized["x"] == 4
|
| 1012 |
+
assert serialized["y"] == 2
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def test_serializing_slice():
|
| 1016 |
+
values = [{"value": value} for value in range(5)]
|
| 1017 |
+
slice = itertools.islice(values, None)
|
| 1018 |
+
|
| 1019 |
+
class ValueSchema(Schema):
|
| 1020 |
+
value = fields.Int()
|
| 1021 |
+
|
| 1022 |
+
serialized = ValueSchema(many=True).dump(slice)
|
| 1023 |
+
assert serialized == values
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
# https://github.com/marshmallow-code/marshmallow/issues/1163
|
| 1027 |
+
def test_nested_field_many_serializing_generator():
|
| 1028 |
+
class MySchema(Schema):
|
| 1029 |
+
name = fields.Str()
|
| 1030 |
+
|
| 1031 |
+
class OtherSchema(Schema):
|
| 1032 |
+
objects = fields.Nested(MySchema, many=True)
|
| 1033 |
+
|
| 1034 |
+
def gen():
|
| 1035 |
+
yield {"name": "foo"}
|
| 1036 |
+
yield {"name": "bar"}
|
| 1037 |
+
|
| 1038 |
+
obj = {"objects": gen()}
|
| 1039 |
+
data = OtherSchema().dump(obj)
|
| 1040 |
+
|
| 1041 |
+
assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}]
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_utils.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime as dt
|
| 2 |
+
from collections import namedtuple
|
| 3 |
+
from copy import copy, deepcopy
|
| 4 |
+
from functools import partial
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
from marshmallow import Schema, fields, utils
|
| 9 |
+
from tests.base import assert_date_equal, assert_time_equal, central
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_missing_singleton_copy():
|
| 13 |
+
assert copy(utils.missing) is utils.missing
|
| 14 |
+
assert deepcopy(utils.missing) is utils.missing
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
PointNT = namedtuple("PointNT", ["x", "y"])
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class PointClass:
|
| 21 |
+
def __init__(self, x, y):
|
| 22 |
+
self.x = x
|
| 23 |
+
self.y = y
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PointDict(dict):
|
| 27 |
+
def __init__(self, x, y):
|
| 28 |
+
super().__init__({"x": x})
|
| 29 |
+
self.y = y
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@pytest.mark.parametrize(
|
| 33 |
+
"obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}]
|
| 34 |
+
)
|
| 35 |
+
def test_get_value_from_object(obj):
|
| 36 |
+
assert utils.get_value(obj, "x") == 24
|
| 37 |
+
assert utils.get_value(obj, "y") == 42
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_get_value_from_namedtuple_with_default():
|
| 41 |
+
p = PointNT(x=42, y=None)
|
| 42 |
+
# Default is only returned if key is not found
|
| 43 |
+
assert utils.get_value(p, "z", default=123) == 123
|
| 44 |
+
# since 'y' is an attribute, None is returned instead of the default
|
| 45 |
+
assert utils.get_value(p, "y", default=123) is None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Triangle:
|
| 49 |
+
def __init__(self, p1, p2, p3):
|
| 50 |
+
self.p1 = p1
|
| 51 |
+
self.p2 = p2
|
| 52 |
+
self.p3 = p3
|
| 53 |
+
self.points = [p1, p2, p3]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_get_value_for_nested_object():
|
| 57 |
+
tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6})
|
| 58 |
+
assert utils.get_value(tri, "p1.x") == 1
|
| 59 |
+
assert utils.get_value(tri, "p2.x") == 3
|
| 60 |
+
assert utils.get_value(tri, "p3.x") == 5
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/62
|
| 64 |
+
def test_get_value_from_dict():
|
| 65 |
+
d = dict(items=["foo", "bar"], keys=["baz", "quux"])
|
| 66 |
+
assert utils.get_value(d, "items") == ["foo", "bar"]
|
| 67 |
+
assert utils.get_value(d, "keys") == ["baz", "quux"]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_get_value():
|
| 71 |
+
lst = [1, 2, 3]
|
| 72 |
+
assert utils.get_value(lst, 1) == 2
|
| 73 |
+
|
| 74 |
+
class MyInt(int):
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
assert utils.get_value(lst, MyInt(1)) == 2
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_set_value():
|
| 81 |
+
d = {}
|
| 82 |
+
utils.set_value(d, "foo", 42)
|
| 83 |
+
assert d == {"foo": 42}
|
| 84 |
+
|
| 85 |
+
d = {}
|
| 86 |
+
utils.set_value(d, "foo.bar", 42)
|
| 87 |
+
assert d == {"foo": {"bar": 42}}
|
| 88 |
+
|
| 89 |
+
d = {"foo": {}}
|
| 90 |
+
utils.set_value(d, "foo.bar", 42)
|
| 91 |
+
assert d == {"foo": {"bar": 42}}
|
| 92 |
+
|
| 93 |
+
d = {"foo": 42}
|
| 94 |
+
with pytest.raises(ValueError):
|
| 95 |
+
utils.set_value(d, "foo.bar", 42)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_is_keyed_tuple():
|
| 99 |
+
Point = namedtuple("Point", ["x", "y"])
|
| 100 |
+
p = Point(24, 42)
|
| 101 |
+
assert utils.is_keyed_tuple(p) is True
|
| 102 |
+
t = (24, 42)
|
| 103 |
+
assert utils.is_keyed_tuple(t) is False
|
| 104 |
+
d = {"x": 42, "y": 24}
|
| 105 |
+
assert utils.is_keyed_tuple(d) is False
|
| 106 |
+
s = "xy"
|
| 107 |
+
assert utils.is_keyed_tuple(s) is False
|
| 108 |
+
lst = [24, 42]
|
| 109 |
+
assert utils.is_keyed_tuple(lst) is False
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_is_collection():
|
| 113 |
+
assert utils.is_collection([1, "foo", {}]) is True
|
| 114 |
+
assert utils.is_collection(("foo", 2.3)) is True
|
| 115 |
+
assert utils.is_collection({"foo": "bar"}) is False
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@pytest.mark.parametrize(
|
| 119 |
+
("value", "expected"),
|
| 120 |
+
[
|
| 121 |
+
(dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"),
|
| 122 |
+
(
|
| 123 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
|
| 124 |
+
"Sun, 10 Nov 2013 01:23:45 +0000",
|
| 125 |
+
),
|
| 126 |
+
(
|
| 127 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central),
|
| 128 |
+
"Sun, 10 Nov 2013 01:23:45 -0600",
|
| 129 |
+
),
|
| 130 |
+
],
|
| 131 |
+
)
|
| 132 |
+
def test_rfc_format(value, expected):
|
| 133 |
+
assert utils.rfcformat(value) == expected
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@pytest.mark.parametrize(
|
| 137 |
+
("value", "expected"),
|
| 138 |
+
[
|
| 139 |
+
(dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"),
|
| 140 |
+
(
|
| 141 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc),
|
| 142 |
+
"2013-11-10T01:23:45.123456+00:00",
|
| 143 |
+
),
|
| 144 |
+
(
|
| 145 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
|
| 146 |
+
"2013-11-10T01:23:45+00:00",
|
| 147 |
+
),
|
| 148 |
+
(
|
| 149 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central),
|
| 150 |
+
"2013-11-10T01:23:45-06:00",
|
| 151 |
+
),
|
| 152 |
+
],
|
| 153 |
+
)
|
| 154 |
+
def test_isoformat(value, expected):
|
| 155 |
+
assert utils.isoformat(value) == expected
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@pytest.mark.parametrize(
|
| 159 |
+
("value", "expected"),
|
| 160 |
+
[
|
| 161 |
+
("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)),
|
| 162 |
+
(
|
| 163 |
+
"Sun, 10 Nov 2013 01:23:45 +0000",
|
| 164 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
|
| 165 |
+
),
|
| 166 |
+
(
|
| 167 |
+
"Sun, 10 Nov 2013 01:23:45 -0600",
|
| 168 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central),
|
| 169 |
+
),
|
| 170 |
+
],
|
| 171 |
+
)
|
| 172 |
+
def test_from_rfc(value, expected):
|
| 173 |
+
result = utils.from_rfc(value)
|
| 174 |
+
assert type(result) is dt.datetime
|
| 175 |
+
assert result == expected
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@pytest.mark.parametrize(
|
| 179 |
+
("value", "expected"),
|
| 180 |
+
[
|
| 181 |
+
("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)),
|
| 182 |
+
(
|
| 183 |
+
"2013-11-10T01:23:45+00:00",
|
| 184 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
|
| 185 |
+
),
|
| 186 |
+
(
|
| 187 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251
|
| 188 |
+
"2013-11-10T01:23:45.123+00:00",
|
| 189 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc),
|
| 190 |
+
),
|
| 191 |
+
(
|
| 192 |
+
"2013-11-10T01:23:45.123456+00:00",
|
| 193 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc),
|
| 194 |
+
),
|
| 195 |
+
(
|
| 196 |
+
"2013-11-10T01:23:45-06:00",
|
| 197 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central),
|
| 198 |
+
),
|
| 199 |
+
],
|
| 200 |
+
)
|
| 201 |
+
def test_from_iso_datetime(value, expected):
|
| 202 |
+
result = utils.from_iso_datetime(value)
|
| 203 |
+
assert type(result) is dt.datetime
|
| 204 |
+
assert result == expected
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def test_from_iso_time_with_microseconds():
|
| 208 |
+
t = dt.time(1, 23, 45, 6789)
|
| 209 |
+
formatted = t.isoformat()
|
| 210 |
+
result = utils.from_iso_time(formatted)
|
| 211 |
+
assert type(result) is dt.time
|
| 212 |
+
assert_time_equal(result, t)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def test_from_iso_time_without_microseconds():
|
| 216 |
+
t = dt.time(1, 23, 45)
|
| 217 |
+
formatted = t.isoformat()
|
| 218 |
+
result = utils.from_iso_time(formatted)
|
| 219 |
+
assert type(result) is dt.time
|
| 220 |
+
assert_time_equal(result, t)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def test_from_iso_date():
|
| 224 |
+
d = dt.date(2014, 8, 21)
|
| 225 |
+
iso_date = d.isoformat()
|
| 226 |
+
result = utils.from_iso_date(iso_date)
|
| 227 |
+
assert type(result) is dt.date
|
| 228 |
+
assert_date_equal(result, d)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
@pytest.mark.parametrize(
|
| 232 |
+
("value", "expected"),
|
| 233 |
+
[
|
| 234 |
+
(1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)),
|
| 235 |
+
(1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)),
|
| 236 |
+
],
|
| 237 |
+
)
|
| 238 |
+
def test_from_timestamp(value, expected):
|
| 239 |
+
result = utils.from_timestamp(value)
|
| 240 |
+
assert type(result) is dt.datetime
|
| 241 |
+
assert result == expected
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def test_from_timestamp_with_negative_value():
|
| 245 |
+
value = -10
|
| 246 |
+
with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"):
|
| 247 |
+
utils.from_timestamp(value)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def test_from_timestamp_with_overflow_value():
|
| 251 |
+
value = 9223372036854775
|
| 252 |
+
with pytest.raises(ValueError):
|
| 253 |
+
utils.from_timestamp(value)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def test_get_func_args():
|
| 257 |
+
def f1(foo, bar):
|
| 258 |
+
pass
|
| 259 |
+
|
| 260 |
+
f2 = partial(f1, "baz")
|
| 261 |
+
|
| 262 |
+
class F3:
|
| 263 |
+
def __call__(self, foo, bar):
|
| 264 |
+
pass
|
| 265 |
+
|
| 266 |
+
f3 = F3()
|
| 267 |
+
|
| 268 |
+
for func in [f1, f2, f3]:
|
| 269 |
+
assert utils.get_func_args(func) == ["foo", "bar"]
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540
|
| 273 |
+
def test_function_field_using_type_annotation():
|
| 274 |
+
def get_split_words(value: str): # noqa
|
| 275 |
+
return value.split(";")
|
| 276 |
+
|
| 277 |
+
class MySchema(Schema):
|
| 278 |
+
friends = fields.Function(deserialize=get_split_words)
|
| 279 |
+
|
| 280 |
+
data = {"friends": "Clark;Alfred;Robin"}
|
| 281 |
+
result = MySchema().load(data)
|
| 282 |
+
assert result == {"friends": ["Clark", "Alfred", "Robin"]}
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_validate.py
ADDED
|
@@ -0,0 +1,983 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for marshmallow.validate"""
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from marshmallow import ValidationError, validate
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@pytest.mark.parametrize(
|
| 11 |
+
"valid_url",
|
| 12 |
+
[
|
| 13 |
+
"http://example.org",
|
| 14 |
+
"https://example.org",
|
| 15 |
+
"ftp://example.org",
|
| 16 |
+
"ftps://example.org",
|
| 17 |
+
"http://example.co.jp",
|
| 18 |
+
"http://www.example.com/a%C2%B1b",
|
| 19 |
+
"http://www.example.com/~username/",
|
| 20 |
+
"http://info.example.com/?fred",
|
| 21 |
+
"http://xn--mgbh0fb.xn--kgbechtv/",
|
| 22 |
+
"http://example.com/blue/red%3Fand+green",
|
| 23 |
+
"http://www.example.com/?array%5Bkey%5D=value",
|
| 24 |
+
"http://xn--rsum-bpad.example.org/",
|
| 25 |
+
"http://123.45.67.8/",
|
| 26 |
+
"http://123.45.67.8:8329/",
|
| 27 |
+
"http://[2001:db8::ff00:42]:8329",
|
| 28 |
+
"http://[2001::1]:8329",
|
| 29 |
+
"http://www.example.com:8000/foo",
|
| 30 |
+
"http://user@example.com",
|
| 31 |
+
"http://user:pass@example.com",
|
| 32 |
+
"http://:pass@example.com",
|
| 33 |
+
"http://@example.com",
|
| 34 |
+
"http://AZaz09-._~%2A!$&'()*+,;=:@example.com",
|
| 35 |
+
],
|
| 36 |
+
)
|
| 37 |
+
def test_url_absolute_valid(valid_url):
|
| 38 |
+
validator = validate.URL(relative=False)
|
| 39 |
+
assert validator(valid_url) == valid_url
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@pytest.mark.parametrize(
|
| 43 |
+
"invalid_url",
|
| 44 |
+
[
|
| 45 |
+
"http:///example.com/",
|
| 46 |
+
"https:///example.com/",
|
| 47 |
+
"https://example.org\\",
|
| 48 |
+
"https://example.org\n",
|
| 49 |
+
"ftp:///example.com/",
|
| 50 |
+
"ftps:///example.com/",
|
| 51 |
+
"http//example.org",
|
| 52 |
+
"http:///",
|
| 53 |
+
"http:/example.org",
|
| 54 |
+
"foo://example.org",
|
| 55 |
+
"../icons/logo.gif",
|
| 56 |
+
"http://2001:db8::ff00:42:8329",
|
| 57 |
+
"http://[192.168.1.1]:8329",
|
| 58 |
+
"abc",
|
| 59 |
+
"..",
|
| 60 |
+
"/",
|
| 61 |
+
" ",
|
| 62 |
+
"",
|
| 63 |
+
None,
|
| 64 |
+
"http://user@pass@example.com",
|
| 65 |
+
"http://@pass@example.com",
|
| 66 |
+
"http://@@example.com",
|
| 67 |
+
"http://^@example.com",
|
| 68 |
+
"http://%0G@example.com",
|
| 69 |
+
"http://%@example.com",
|
| 70 |
+
],
|
| 71 |
+
)
|
| 72 |
+
def test_url_absolute_invalid(invalid_url):
|
| 73 |
+
validator = validate.URL(relative=False)
|
| 74 |
+
with pytest.raises(ValidationError):
|
| 75 |
+
validator(invalid_url)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@pytest.mark.parametrize(
|
| 79 |
+
"valid_url",
|
| 80 |
+
[
|
| 81 |
+
"http://example.org",
|
| 82 |
+
"http://123.45.67.8/",
|
| 83 |
+
"http://example.com/foo/bar/../baz",
|
| 84 |
+
"https://example.com/../icons/logo.gif",
|
| 85 |
+
"http://example.com/./icons/logo.gif",
|
| 86 |
+
"ftp://example.com/../../../../g",
|
| 87 |
+
"http://example.com/g?y/./x",
|
| 88 |
+
"/foo/bar",
|
| 89 |
+
"/foo?bar",
|
| 90 |
+
"/foo?bar#baz",
|
| 91 |
+
],
|
| 92 |
+
)
|
| 93 |
+
def test_url_relative_valid(valid_url):
|
| 94 |
+
validator = validate.URL(relative=True)
|
| 95 |
+
assert validator(valid_url) == valid_url
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@pytest.mark.parametrize( # noqa: W605
|
| 99 |
+
"invalid_url",
|
| 100 |
+
[
|
| 101 |
+
"http//example.org",
|
| 102 |
+
"http://example.org\n",
|
| 103 |
+
"suppliers.html",
|
| 104 |
+
"../icons/logo.gif",
|
| 105 |
+
"icons/logo.gif",
|
| 106 |
+
"../.../g",
|
| 107 |
+
"...",
|
| 108 |
+
"\\",
|
| 109 |
+
" ",
|
| 110 |
+
"",
|
| 111 |
+
None,
|
| 112 |
+
],
|
| 113 |
+
)
|
| 114 |
+
def test_url_relative_invalid(invalid_url):
|
| 115 |
+
validator = validate.URL(relative=True)
|
| 116 |
+
with pytest.raises(ValidationError):
|
| 117 |
+
validator(invalid_url)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@pytest.mark.parametrize(
|
| 121 |
+
"valid_url",
|
| 122 |
+
[
|
| 123 |
+
"/foo/bar",
|
| 124 |
+
"/foo?bar",
|
| 125 |
+
"?bar",
|
| 126 |
+
"/foo?bar#baz",
|
| 127 |
+
],
|
| 128 |
+
)
|
| 129 |
+
def test_url_relative_only_valid(valid_url):
|
| 130 |
+
validator = validate.URL(relative=True, absolute=False)
|
| 131 |
+
assert validator(valid_url) == valid_url
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@pytest.mark.parametrize(
|
| 135 |
+
"invalid_url",
|
| 136 |
+
[
|
| 137 |
+
"http//example.org",
|
| 138 |
+
"http://example.org\n",
|
| 139 |
+
"suppliers.html",
|
| 140 |
+
"../icons/logo.gif",
|
| 141 |
+
"icons/logo.gif",
|
| 142 |
+
"../.../g",
|
| 143 |
+
"...",
|
| 144 |
+
"\\",
|
| 145 |
+
" ",
|
| 146 |
+
"",
|
| 147 |
+
"http://example.org",
|
| 148 |
+
"http://123.45.67.8/",
|
| 149 |
+
"http://example.com/foo/bar/../baz",
|
| 150 |
+
"https://example.com/../icons/logo.gif",
|
| 151 |
+
"http://example.com/./icons/logo.gif",
|
| 152 |
+
"ftp://example.com/../../../../g",
|
| 153 |
+
"http://example.com/g?y/./x",
|
| 154 |
+
],
|
| 155 |
+
)
|
| 156 |
+
def test_url_relative_only_invalid(invalid_url):
|
| 157 |
+
validator = validate.URL(relative=True, absolute=False)
|
| 158 |
+
with pytest.raises(ValidationError):
|
| 159 |
+
validator(invalid_url)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@pytest.mark.parametrize(
|
| 163 |
+
"valid_url",
|
| 164 |
+
[
|
| 165 |
+
"http://example.org",
|
| 166 |
+
"http://123.45.67.8/",
|
| 167 |
+
"http://example",
|
| 168 |
+
"http://example.",
|
| 169 |
+
"http://example:80",
|
| 170 |
+
"http://user.name:pass.word@example",
|
| 171 |
+
"http://example/foo/bar",
|
| 172 |
+
],
|
| 173 |
+
)
|
| 174 |
+
def test_url_dont_require_tld_valid(valid_url):
|
| 175 |
+
validator = validate.URL(require_tld=False)
|
| 176 |
+
assert validator(valid_url) == valid_url
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@pytest.mark.parametrize(
|
| 180 |
+
"invalid_url",
|
| 181 |
+
[
|
| 182 |
+
"http//example",
|
| 183 |
+
"http://example\n",
|
| 184 |
+
"http://.example.org",
|
| 185 |
+
"http:///foo/bar",
|
| 186 |
+
"http:// /foo/bar",
|
| 187 |
+
"",
|
| 188 |
+
None,
|
| 189 |
+
],
|
| 190 |
+
)
|
| 191 |
+
def test_url_dont_require_tld_invalid(invalid_url):
|
| 192 |
+
validator = validate.URL(require_tld=False)
|
| 193 |
+
with pytest.raises(ValidationError):
|
| 194 |
+
validator(invalid_url)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def test_url_custom_scheme():
|
| 198 |
+
validator = validate.URL()
|
| 199 |
+
# By default, ws not allowed
|
| 200 |
+
url = "ws://test.test"
|
| 201 |
+
with pytest.raises(ValidationError):
|
| 202 |
+
validator(url)
|
| 203 |
+
|
| 204 |
+
validator = validate.URL(schemes={"http", "https", "ws"})
|
| 205 |
+
assert validator(url) == url
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def test_url_relative_and_custom_schemes():
|
| 209 |
+
validator = validate.URL(relative=True)
|
| 210 |
+
# By default, ws not allowed
|
| 211 |
+
url = "ws://test.test"
|
| 212 |
+
with pytest.raises(ValidationError):
|
| 213 |
+
validator(url)
|
| 214 |
+
|
| 215 |
+
validator = validate.URL(relative=True, schemes={"http", "https", "ws"})
|
| 216 |
+
assert validator(url) == url
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def test_url_custom_message():
|
| 220 |
+
validator = validate.URL(error="{input} ain't an URL")
|
| 221 |
+
with pytest.raises(ValidationError, match="invalid ain't an URL"):
|
| 222 |
+
validator("invalid")
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def test_url_repr():
|
| 226 |
+
assert repr(
|
| 227 |
+
validate.URL(relative=False, error=None)
|
| 228 |
+
) == "<URL(relative=False, absolute=True, error={!r})>".format("Not a valid URL.")
|
| 229 |
+
assert repr(
|
| 230 |
+
validate.URL(relative=True, error="foo")
|
| 231 |
+
) == "<URL(relative=True, absolute=True, error={!r})>".format("foo")
|
| 232 |
+
assert repr(
|
| 233 |
+
validate.URL(relative=True, absolute=False, error="foo")
|
| 234 |
+
) == "<URL(relative=True, absolute=False, error={!r})>".format("foo")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def test_url_rejects_invalid_relative_usage():
|
| 238 |
+
with pytest.raises(
|
| 239 |
+
ValueError,
|
| 240 |
+
match="URL validation cannot set both relative and absolute to False",
|
| 241 |
+
):
|
| 242 |
+
validate.URL(relative=False, absolute=False)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@pytest.mark.parametrize(
|
| 246 |
+
"valid_email",
|
| 247 |
+
[
|
| 248 |
+
"niceandsimple@example.com",
|
| 249 |
+
"NiCeAnDsImPlE@eXaMpLe.CoM",
|
| 250 |
+
"very.common@example.com",
|
| 251 |
+
"a.little.lengthy.but.fine@a.iana-servers.net",
|
| 252 |
+
"disposable.style.email.with+symbol@example.com",
|
| 253 |
+
'"very.unusual.@.unusual.com"@example.com',
|
| 254 |
+
"!#$%&'*+-/=?^_`{}|~@example.org",
|
| 255 |
+
"niceandsimple@[64.233.160.0]",
|
| 256 |
+
"niceandsimple@localhost",
|
| 257 |
+
"josé@blah.com",
|
| 258 |
+
"δοκ.ιμή@παράδειγμα.δοκιμή",
|
| 259 |
+
],
|
| 260 |
+
)
|
| 261 |
+
def test_email_valid(valid_email):
|
| 262 |
+
validator = validate.Email()
|
| 263 |
+
assert validator(valid_email) == valid_email
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@pytest.mark.parametrize(
|
| 267 |
+
"invalid_email",
|
| 268 |
+
[
|
| 269 |
+
"niceandsimple\n@example.com",
|
| 270 |
+
"NiCeAnDsImPlE@eXaMpLe.CoM\n",
|
| 271 |
+
'a"b(c)d,e:f;g<h>i[j\\k]l@example.com',
|
| 272 |
+
'just"not"right@example.com',
|
| 273 |
+
'this is"not\allowed@example.com',
|
| 274 |
+
'this\\ still\\"not\\\\allowed@example.com',
|
| 275 |
+
'"much.more unusual"@example.com',
|
| 276 |
+
'"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com',
|
| 277 |
+
'" "@example.org',
|
| 278 |
+
"user@example",
|
| 279 |
+
"@nouser.com",
|
| 280 |
+
"example.com",
|
| 281 |
+
"user",
|
| 282 |
+
"",
|
| 283 |
+
None,
|
| 284 |
+
],
|
| 285 |
+
)
|
| 286 |
+
def test_email_invalid(invalid_email):
|
| 287 |
+
validator = validate.Email()
|
| 288 |
+
with pytest.raises(ValidationError):
|
| 289 |
+
validator(invalid_email)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def test_email_custom_message():
|
| 293 |
+
validator = validate.Email(error="{input} is not an email addy.")
|
| 294 |
+
with pytest.raises(ValidationError, match="invalid is not an email addy."):
|
| 295 |
+
validator("invalid")
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def test_email_repr():
|
| 299 |
+
assert repr(validate.Email(error=None)) == "<Email(error={!r})>".format(
|
| 300 |
+
"Not a valid email address."
|
| 301 |
+
)
|
| 302 |
+
assert repr(validate.Email(error="foo")) == "<Email(error={!r})>".format("foo")
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def test_range_min():
|
| 306 |
+
assert validate.Range(1, 2)(1) == 1
|
| 307 |
+
assert validate.Range(0)(1) == 1
|
| 308 |
+
assert validate.Range()(1) == 1
|
| 309 |
+
assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1
|
| 310 |
+
assert validate.Range(1, 1)(1) == 1
|
| 311 |
+
|
| 312 |
+
with pytest.raises(ValidationError, match="Must be greater than or equal to 2"):
|
| 313 |
+
validate.Range(2, 3)(1)
|
| 314 |
+
with pytest.raises(ValidationError, match="Must be greater than or equal to 2"):
|
| 315 |
+
validate.Range(2)(1)
|
| 316 |
+
with pytest.raises(ValidationError, match="Must be greater than 1"):
|
| 317 |
+
validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1)
|
| 318 |
+
with pytest.raises(ValidationError, match="less than 1"):
|
| 319 |
+
validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def test_range_max():
|
| 323 |
+
assert validate.Range(1, 2)(2) == 2
|
| 324 |
+
assert validate.Range(None, 2)(2) == 2
|
| 325 |
+
assert validate.Range()(2) == 2
|
| 326 |
+
assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2
|
| 327 |
+
assert validate.Range(2, 2)(2) == 2
|
| 328 |
+
|
| 329 |
+
with pytest.raises(ValidationError, match="less than or equal to 1"):
|
| 330 |
+
validate.Range(0, 1)(2)
|
| 331 |
+
with pytest.raises(ValidationError, match="less than or equal to 1"):
|
| 332 |
+
validate.Range(None, 1)(2)
|
| 333 |
+
with pytest.raises(ValidationError, match="less than 2"):
|
| 334 |
+
validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2)
|
| 335 |
+
with pytest.raises(ValidationError, match="greater than 2"):
|
| 336 |
+
validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def test_range_custom_message():
|
| 340 |
+
v = validate.Range(2, 3, error="{input} is not between {min} and {max}")
|
| 341 |
+
with pytest.raises(ValidationError, match="1 is not between 2 and 3"):
|
| 342 |
+
v(1)
|
| 343 |
+
|
| 344 |
+
v = validate.Range(2, None, error="{input} is less than {min}")
|
| 345 |
+
with pytest.raises(ValidationError, match="1 is less than 2"):
|
| 346 |
+
v(1)
|
| 347 |
+
|
| 348 |
+
v = validate.Range(None, 3, error="{input} is greater than {max}")
|
| 349 |
+
with pytest.raises(ValidationError, match="4 is greater than 3"):
|
| 350 |
+
v(4)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def test_range_repr():
|
| 354 |
+
assert (
|
| 355 |
+
repr(
|
| 356 |
+
validate.Range(
|
| 357 |
+
min=None, max=None, error=None, min_inclusive=True, max_inclusive=True
|
| 358 |
+
)
|
| 359 |
+
)
|
| 360 |
+
== "<Range(min=None, max=None, min_inclusive=True, max_inclusive=True, error=None)>" # noqa: B950
|
| 361 |
+
)
|
| 362 |
+
assert (
|
| 363 |
+
repr(
|
| 364 |
+
validate.Range(
|
| 365 |
+
min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False
|
| 366 |
+
)
|
| 367 |
+
)
|
| 368 |
+
== "<Range(min=1, max=3, min_inclusive=False, max_inclusive=False, error={!r})>".format( # noqa: B950
|
| 369 |
+
"foo"
|
| 370 |
+
)
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def test_length_min():
|
| 375 |
+
assert validate.Length(3, 5)("foo") == "foo"
|
| 376 |
+
assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3]
|
| 377 |
+
assert validate.Length(0)("a") == "a"
|
| 378 |
+
assert validate.Length(0)([1]) == [1]
|
| 379 |
+
assert validate.Length()("") == ""
|
| 380 |
+
assert validate.Length()([]) == []
|
| 381 |
+
assert validate.Length(1, 1)("a") == "a"
|
| 382 |
+
assert validate.Length(1, 1)([1]) == [1]
|
| 383 |
+
|
| 384 |
+
with pytest.raises(ValidationError):
|
| 385 |
+
validate.Length(4, 5)("foo")
|
| 386 |
+
with pytest.raises(ValidationError):
|
| 387 |
+
validate.Length(4, 5)([1, 2, 3])
|
| 388 |
+
with pytest.raises(ValidationError):
|
| 389 |
+
validate.Length(5)("foo")
|
| 390 |
+
with pytest.raises(ValidationError):
|
| 391 |
+
validate.Length(5)([1, 2, 3])
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def test_length_max():
|
| 395 |
+
assert validate.Length(1, 3)("foo") == "foo"
|
| 396 |
+
assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3]
|
| 397 |
+
assert validate.Length(None, 1)("a") == "a"
|
| 398 |
+
assert validate.Length(None, 1)([1]) == [1]
|
| 399 |
+
assert validate.Length()("") == ""
|
| 400 |
+
assert validate.Length()([]) == []
|
| 401 |
+
assert validate.Length(2, 2)("ab") == "ab"
|
| 402 |
+
assert validate.Length(2, 2)([1, 2]) == [1, 2]
|
| 403 |
+
|
| 404 |
+
with pytest.raises(ValidationError):
|
| 405 |
+
validate.Length(1, 2)("foo")
|
| 406 |
+
with pytest.raises(ValidationError):
|
| 407 |
+
validate.Length(1, 2)([1, 2, 3])
|
| 408 |
+
with pytest.raises(ValidationError):
|
| 409 |
+
validate.Length(None, 2)("foo")
|
| 410 |
+
with pytest.raises(ValidationError):
|
| 411 |
+
validate.Length(None, 2)([1, 2, 3])
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def test_length_equal():
|
| 415 |
+
assert validate.Length(equal=3)("foo") == "foo"
|
| 416 |
+
assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3]
|
| 417 |
+
assert validate.Length(equal=None)("") == ""
|
| 418 |
+
assert validate.Length(equal=None)([]) == []
|
| 419 |
+
|
| 420 |
+
with pytest.raises(ValidationError):
|
| 421 |
+
validate.Length(equal=2)("foo")
|
| 422 |
+
with pytest.raises(ValidationError):
|
| 423 |
+
validate.Length(equal=2)([1, 2, 3])
|
| 424 |
+
|
| 425 |
+
with pytest.raises(ValueError):
|
| 426 |
+
validate.Length(1, None, equal=3)("foo")
|
| 427 |
+
with pytest.raises(ValueError):
|
| 428 |
+
validate.Length(None, 5, equal=3)("foo")
|
| 429 |
+
with pytest.raises(ValueError):
|
| 430 |
+
validate.Length(1, 5, equal=3)("foo")
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def test_length_custom_message():
|
| 434 |
+
v = validate.Length(5, 6, error="{input} is not between {min} and {max}")
|
| 435 |
+
with pytest.raises(ValidationError, match="foo is not between 5 and 6"):
|
| 436 |
+
v("foo")
|
| 437 |
+
|
| 438 |
+
v = validate.Length(5, None, error="{input} is shorter than {min}")
|
| 439 |
+
with pytest.raises(ValidationError, match="foo is shorter than 5"):
|
| 440 |
+
v("foo")
|
| 441 |
+
|
| 442 |
+
v = validate.Length(None, 2, error="{input} is longer than {max}")
|
| 443 |
+
with pytest.raises(ValidationError, match="foo is longer than 2"):
|
| 444 |
+
v("foo")
|
| 445 |
+
|
| 446 |
+
v = validate.Length(None, None, equal=4, error="{input} does not have {equal}")
|
| 447 |
+
with pytest.raises(ValidationError, match="foo does not have 4"):
|
| 448 |
+
v("foo")
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def test_length_repr():
|
| 452 |
+
assert (
|
| 453 |
+
repr(validate.Length(min=None, max=None, error=None, equal=None))
|
| 454 |
+
== "<Length(min=None, max=None, equal=None, error=None)>"
|
| 455 |
+
)
|
| 456 |
+
assert repr(
|
| 457 |
+
validate.Length(min=1, max=3, error="foo", equal=None)
|
| 458 |
+
) == "<Length(min=1, max=3, equal=None, error={!r})>".format("foo")
|
| 459 |
+
assert repr(
|
| 460 |
+
validate.Length(min=None, max=None, error="foo", equal=5)
|
| 461 |
+
) == "<Length(min=None, max=None, equal=5, error={!r})>".format("foo")
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def test_equal():
|
| 465 |
+
assert validate.Equal("a")("a") == "a"
|
| 466 |
+
assert validate.Equal(1)(1) == 1
|
| 467 |
+
assert validate.Equal([1])([1]) == [1]
|
| 468 |
+
|
| 469 |
+
with pytest.raises(ValidationError):
|
| 470 |
+
validate.Equal("b")("a")
|
| 471 |
+
with pytest.raises(ValidationError):
|
| 472 |
+
validate.Equal(2)(1)
|
| 473 |
+
with pytest.raises(ValidationError):
|
| 474 |
+
validate.Equal([2])([1])
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def test_equal_custom_message():
|
| 478 |
+
v = validate.Equal("a", error="{input} is not equal to {other}.")
|
| 479 |
+
with pytest.raises(ValidationError, match="b is not equal to a."):
|
| 480 |
+
v("b")
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def test_equal_repr():
|
| 484 |
+
assert repr(
|
| 485 |
+
validate.Equal(comparable=123, error=None)
|
| 486 |
+
) == "<Equal(comparable=123, error={!r})>".format("Must be equal to {other}.")
|
| 487 |
+
assert repr(
|
| 488 |
+
validate.Equal(comparable=123, error="foo")
|
| 489 |
+
) == "<Equal(comparable=123, error={!r})>".format("foo")
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def test_regexp_str():
|
| 493 |
+
assert validate.Regexp(r"a")("a") == "a"
|
| 494 |
+
assert validate.Regexp(r"\w")("_") == "_"
|
| 495 |
+
assert validate.Regexp(r"\s")(" ") == " "
|
| 496 |
+
assert validate.Regexp(r"1")("1") == "1"
|
| 497 |
+
assert validate.Regexp(r"[0-9]+")("1") == "1"
|
| 498 |
+
assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A"
|
| 499 |
+
|
| 500 |
+
with pytest.raises(ValidationError):
|
| 501 |
+
validate.Regexp(r"[0-9]+")("a")
|
| 502 |
+
with pytest.raises(ValidationError):
|
| 503 |
+
validate.Regexp(r"[a-z]+")("1")
|
| 504 |
+
with pytest.raises(ValidationError):
|
| 505 |
+
validate.Regexp(r"a")("A")
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def test_regexp_compile():
|
| 509 |
+
assert validate.Regexp(re.compile(r"a"))("a") == "a"
|
| 510 |
+
assert validate.Regexp(re.compile(r"\w"))("_") == "_"
|
| 511 |
+
assert validate.Regexp(re.compile(r"\s"))(" ") == " "
|
| 512 |
+
assert validate.Regexp(re.compile(r"1"))("1") == "1"
|
| 513 |
+
assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1"
|
| 514 |
+
assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A"
|
| 515 |
+
assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A"
|
| 516 |
+
|
| 517 |
+
with pytest.raises(ValidationError):
|
| 518 |
+
validate.Regexp(re.compile(r"[0-9]+"))("a")
|
| 519 |
+
with pytest.raises(ValidationError):
|
| 520 |
+
validate.Regexp(re.compile(r"[a-z]+"))("1")
|
| 521 |
+
with pytest.raises(ValidationError):
|
| 522 |
+
validate.Regexp(re.compile(r"a"))("A")
|
| 523 |
+
with pytest.raises(ValidationError):
|
| 524 |
+
validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A")
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def test_regexp_custom_message():
|
| 528 |
+
rex = r"[0-9]+"
|
| 529 |
+
v = validate.Regexp(rex, error="{input} does not match {regex}")
|
| 530 |
+
with pytest.raises(ValidationError, match="a does not match"):
|
| 531 |
+
v("a")
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def test_regexp_repr():
|
| 535 |
+
assert repr(
|
| 536 |
+
validate.Regexp(regex="abc", flags=0, error=None)
|
| 537 |
+
) == "<Regexp(regex={!r}, error={!r})>".format(
|
| 538 |
+
re.compile("abc"), "String does not match expected pattern."
|
| 539 |
+
)
|
| 540 |
+
assert repr(
|
| 541 |
+
validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo")
|
| 542 |
+
) == "<Regexp(regex={!r}, error={!r})>".format(
|
| 543 |
+
re.compile("abc", re.IGNORECASE), "foo"
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def test_predicate():
|
| 548 |
+
class Dummy:
|
| 549 |
+
def _true(self):
|
| 550 |
+
return True
|
| 551 |
+
|
| 552 |
+
def _false(self):
|
| 553 |
+
return False
|
| 554 |
+
|
| 555 |
+
def _list(self):
|
| 556 |
+
return [1, 2, 3]
|
| 557 |
+
|
| 558 |
+
def _empty(self):
|
| 559 |
+
return []
|
| 560 |
+
|
| 561 |
+
def _identity(self, arg):
|
| 562 |
+
return arg
|
| 563 |
+
|
| 564 |
+
d = Dummy()
|
| 565 |
+
|
| 566 |
+
assert validate.Predicate("_true")(d) == d
|
| 567 |
+
assert validate.Predicate("_list")(d) == d
|
| 568 |
+
assert validate.Predicate("_identity", arg=True)(d) == d
|
| 569 |
+
assert validate.Predicate("_identity", arg=1)(d) == d
|
| 570 |
+
assert validate.Predicate("_identity", arg="abc")(d) == d
|
| 571 |
+
|
| 572 |
+
with pytest.raises(ValidationError, match="Invalid input."):
|
| 573 |
+
validate.Predicate("_false")(d)
|
| 574 |
+
with pytest.raises(ValidationError):
|
| 575 |
+
validate.Predicate("_empty")(d)
|
| 576 |
+
with pytest.raises(ValidationError):
|
| 577 |
+
validate.Predicate("_identity", arg=False)(d)
|
| 578 |
+
with pytest.raises(ValidationError):
|
| 579 |
+
validate.Predicate("_identity", arg=0)(d)
|
| 580 |
+
with pytest.raises(ValidationError):
|
| 581 |
+
validate.Predicate("_identity", arg="")(d)
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def test_predicate_custom_message():
|
| 585 |
+
class Dummy:
|
| 586 |
+
def _false(self):
|
| 587 |
+
return False
|
| 588 |
+
|
| 589 |
+
def __str__(self):
|
| 590 |
+
return "Dummy"
|
| 591 |
+
|
| 592 |
+
d = Dummy()
|
| 593 |
+
with pytest.raises(ValidationError, match="Dummy._false is invalid!"):
|
| 594 |
+
validate.Predicate("_false", error="{input}.{method} is invalid!")(d)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def test_predicate_repr():
|
| 598 |
+
assert repr(
|
| 599 |
+
validate.Predicate(method="foo", error=None)
|
| 600 |
+
) == "<Predicate(method={!r}, kwargs={!r}, error={!r})>".format(
|
| 601 |
+
"foo", {}, "Invalid input."
|
| 602 |
+
)
|
| 603 |
+
assert repr(
|
| 604 |
+
validate.Predicate(method="foo", error="bar", zoo=1)
|
| 605 |
+
) == "<Predicate(method={!r}, kwargs={!r}, error={!r})>".format(
|
| 606 |
+
"foo", {"zoo": 1}, "bar"
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def test_noneof():
|
| 611 |
+
assert validate.NoneOf([1, 2, 3])(4) == 4
|
| 612 |
+
assert validate.NoneOf("abc")("d") == "d"
|
| 613 |
+
assert validate.NoneOf("")([]) == []
|
| 614 |
+
assert validate.NoneOf([])("") == ""
|
| 615 |
+
assert validate.NoneOf([])([]) == []
|
| 616 |
+
assert validate.NoneOf([1, 2, 3])(None) is None
|
| 617 |
+
|
| 618 |
+
with pytest.raises(ValidationError, match="Invalid input."):
|
| 619 |
+
validate.NoneOf([1, 2, 3])(3)
|
| 620 |
+
with pytest.raises(ValidationError):
|
| 621 |
+
validate.NoneOf("abc")("c")
|
| 622 |
+
with pytest.raises(ValidationError):
|
| 623 |
+
validate.NoneOf([1, 2, None])(None)
|
| 624 |
+
with pytest.raises(ValidationError):
|
| 625 |
+
validate.NoneOf("")("")
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def test_noneof_custom_message():
|
| 629 |
+
with pytest.raises(ValidationError, match="<not valid>"):
|
| 630 |
+
validate.NoneOf([1, 2], error="<not valid>")(1)
|
| 631 |
+
|
| 632 |
+
none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}")
|
| 633 |
+
with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"):
|
| 634 |
+
none_of(1)
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def test_noneof_repr():
|
| 638 |
+
assert repr(
|
| 639 |
+
validate.NoneOf(iterable=[1, 2, 3], error=None)
|
| 640 |
+
) == "<NoneOf(iterable=[1, 2, 3], error={!r})>".format("Invalid input.")
|
| 641 |
+
assert repr(
|
| 642 |
+
validate.NoneOf(iterable=[1, 2, 3], error="foo")
|
| 643 |
+
) == "<NoneOf(iterable=[1, 2, 3], error={!r})>".format("foo")
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def test_oneof():
|
| 647 |
+
assert validate.OneOf([1, 2, 3])(2) == 2
|
| 648 |
+
assert validate.OneOf("abc")("b") == "b"
|
| 649 |
+
assert validate.OneOf("")("") == ""
|
| 650 |
+
assert validate.OneOf(dict(a=0, b=1))("a") == "a"
|
| 651 |
+
assert validate.OneOf((1, 2, None))(None) is None
|
| 652 |
+
|
| 653 |
+
with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."):
|
| 654 |
+
validate.OneOf([1, 2, 3])(4)
|
| 655 |
+
with pytest.raises(ValidationError):
|
| 656 |
+
validate.OneOf("abc")("d")
|
| 657 |
+
with pytest.raises(ValidationError):
|
| 658 |
+
validate.OneOf((1, 2, 3))(None)
|
| 659 |
+
with pytest.raises(ValidationError):
|
| 660 |
+
validate.OneOf([])([])
|
| 661 |
+
with pytest.raises(ValidationError):
|
| 662 |
+
validate.OneOf(())(())
|
| 663 |
+
with pytest.raises(ValidationError):
|
| 664 |
+
validate.OneOf(dict(a=0, b=1))(0)
|
| 665 |
+
with pytest.raises(ValidationError):
|
| 666 |
+
validate.OneOf("123")(1)
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def test_oneof_options():
|
| 670 |
+
oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"])
|
| 671 |
+
expected = [("1", "one"), ("2", "two"), ("3", "three")]
|
| 672 |
+
assert list(oneof.options()) == expected
|
| 673 |
+
|
| 674 |
+
oneof = validate.OneOf([1, 2, 3], ["one", "two"])
|
| 675 |
+
expected = [("1", "one"), ("2", "two"), ("3", "")]
|
| 676 |
+
assert list(oneof.options()) == expected
|
| 677 |
+
|
| 678 |
+
oneof = validate.OneOf([1, 2], ["one", "two", "three"])
|
| 679 |
+
expected = [("1", "one"), ("2", "two"), ("", "three")]
|
| 680 |
+
assert list(oneof.options()) == expected
|
| 681 |
+
|
| 682 |
+
oneof = validate.OneOf([1, 2])
|
| 683 |
+
expected = [("1", ""), ("2", "")]
|
| 684 |
+
assert list(oneof.options()) == expected
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def test_oneof_text():
|
| 688 |
+
oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"])
|
| 689 |
+
assert oneof.choices_text == "1, 2, 3"
|
| 690 |
+
assert oneof.labels_text == "one, two, three"
|
| 691 |
+
|
| 692 |
+
oneof = validate.OneOf([1], ["one"])
|
| 693 |
+
assert oneof.choices_text == "1"
|
| 694 |
+
assert oneof.labels_text == "one"
|
| 695 |
+
|
| 696 |
+
oneof = validate.OneOf(dict(a=0, b=1))
|
| 697 |
+
assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b"
|
| 698 |
+
assert oneof.labels_text == ""
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def test_oneof_custom_message():
|
| 702 |
+
oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}")
|
| 703 |
+
expected = "4 is not one of 1, 2, 3"
|
| 704 |
+
with pytest.raises(ValidationError):
|
| 705 |
+
oneof(4)
|
| 706 |
+
assert expected in str(expected)
|
| 707 |
+
|
| 708 |
+
oneof = validate.OneOf(
|
| 709 |
+
[1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}"
|
| 710 |
+
)
|
| 711 |
+
expected = "4 is not one of one, two, three"
|
| 712 |
+
with pytest.raises(ValidationError):
|
| 713 |
+
oneof(4)
|
| 714 |
+
assert expected in str(expected)
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
def test_oneof_repr():
|
| 718 |
+
assert repr(
|
| 719 |
+
validate.OneOf(choices=[1, 2, 3], labels=None, error=None)
|
| 720 |
+
) == "<OneOf(choices=[1, 2, 3], labels=[], error={!r})>".format(
|
| 721 |
+
"Must be one of: {choices}."
|
| 722 |
+
)
|
| 723 |
+
assert repr(
|
| 724 |
+
validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo")
|
| 725 |
+
) == "<OneOf(choices=[1, 2, 3], labels={!r}, error={!r})>".format(
|
| 726 |
+
["a", "b", "c"], "foo"
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
def test_containsonly_in_list():
|
| 731 |
+
assert validate.ContainsOnly([])([]) == []
|
| 732 |
+
assert validate.ContainsOnly([1, 2, 3])([1]) == [1]
|
| 733 |
+
assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1]
|
| 734 |
+
assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2]
|
| 735 |
+
assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1]
|
| 736 |
+
assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3]
|
| 737 |
+
assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2]
|
| 738 |
+
assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1]
|
| 739 |
+
assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1]
|
| 740 |
+
assert validate.ContainsOnly([1, 2, 3])([]) == []
|
| 741 |
+
|
| 742 |
+
with pytest.raises(
|
| 743 |
+
ValidationError,
|
| 744 |
+
match="One or more of the choices you made was not in: 1, 2, 3.",
|
| 745 |
+
):
|
| 746 |
+
validate.ContainsOnly([1, 2, 3])([4])
|
| 747 |
+
with pytest.raises(ValidationError):
|
| 748 |
+
validate.ContainsOnly([])([1])
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
def test_contains_only_unhashable_types():
|
| 752 |
+
assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]]
|
| 753 |
+
assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]]
|
| 754 |
+
assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]]
|
| 755 |
+
assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]]
|
| 756 |
+
assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]]
|
| 757 |
+
assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]]
|
| 758 |
+
assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]]
|
| 759 |
+
assert validate.ContainsOnly([[1], [2], [3]])([]) == []
|
| 760 |
+
|
| 761 |
+
with pytest.raises(ValidationError):
|
| 762 |
+
validate.ContainsOnly([[1], [2], [3]])([[4]])
|
| 763 |
+
with pytest.raises(ValidationError):
|
| 764 |
+
validate.ContainsOnly([])([1])
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
def test_containsonly_in_tuple():
|
| 768 |
+
assert validate.ContainsOnly(())(()) == ()
|
| 769 |
+
assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,)
|
| 770 |
+
assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1)
|
| 771 |
+
assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2)
|
| 772 |
+
assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1)
|
| 773 |
+
assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3)
|
| 774 |
+
assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2)
|
| 775 |
+
assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1)
|
| 776 |
+
assert validate.ContainsOnly((1, 2, 3))(()) == tuple()
|
| 777 |
+
with pytest.raises(ValidationError):
|
| 778 |
+
validate.ContainsOnly((1, 2, 3))((4,))
|
| 779 |
+
with pytest.raises(ValidationError):
|
| 780 |
+
validate.ContainsOnly(())((1,))
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
def test_contains_only_in_string():
|
| 784 |
+
assert validate.ContainsOnly("")("") == ""
|
| 785 |
+
assert validate.ContainsOnly("abc")("a") == "a"
|
| 786 |
+
assert validate.ContainsOnly("aab")("aa") == "aa"
|
| 787 |
+
assert validate.ContainsOnly("abc")("ab") == "ab"
|
| 788 |
+
assert validate.ContainsOnly("abc")("ba") == "ba"
|
| 789 |
+
assert validate.ContainsOnly("abc")("abc") == "abc"
|
| 790 |
+
assert validate.ContainsOnly("abc")("cab") == "cab"
|
| 791 |
+
assert validate.ContainsOnly("abc")("bca") == "bca"
|
| 792 |
+
assert validate.ContainsOnly("abc")("") == ""
|
| 793 |
+
|
| 794 |
+
with pytest.raises(ValidationError):
|
| 795 |
+
validate.ContainsOnly("abc")("d")
|
| 796 |
+
with pytest.raises(ValidationError):
|
| 797 |
+
validate.ContainsOnly("")("a")
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
def test_containsonly_custom_message():
|
| 801 |
+
containsonly = validate.ContainsOnly(
|
| 802 |
+
[1, 2, 3], error="{input} is not one of {choices}"
|
| 803 |
+
)
|
| 804 |
+
expected = "4, 5 is not one of 1, 2, 3"
|
| 805 |
+
with pytest.raises(ValidationError):
|
| 806 |
+
containsonly([4, 5])
|
| 807 |
+
assert expected in str(expected)
|
| 808 |
+
|
| 809 |
+
containsonly = validate.ContainsOnly(
|
| 810 |
+
[1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}"
|
| 811 |
+
)
|
| 812 |
+
expected = "4, 5 is not one of one, two, three"
|
| 813 |
+
with pytest.raises(ValidationError):
|
| 814 |
+
containsonly([4, 5])
|
| 815 |
+
assert expected in str(expected)
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def test_containsonly_repr():
|
| 819 |
+
assert repr(
|
| 820 |
+
validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None)
|
| 821 |
+
) == "<ContainsOnly(choices=[1, 2, 3], labels=[], error={!r})>".format(
|
| 822 |
+
"One or more of the choices you made was not in: {choices}."
|
| 823 |
+
)
|
| 824 |
+
assert repr(
|
| 825 |
+
validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo")
|
| 826 |
+
) == "<ContainsOnly(choices=[1, 2, 3], labels={!r}, error={!r})>".format(
|
| 827 |
+
["a", "b", "c"], "foo"
|
| 828 |
+
)
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
def test_containsnoneof_error_message():
|
| 832 |
+
with pytest.raises(
|
| 833 |
+
ValidationError, match="One or more of the choices you made was in: 1"
|
| 834 |
+
):
|
| 835 |
+
validate.ContainsNoneOf([1])([1])
|
| 836 |
+
|
| 837 |
+
with pytest.raises(
|
| 838 |
+
ValidationError, match="One or more of the choices you made was in: 1, 2, 3"
|
| 839 |
+
):
|
| 840 |
+
validate.ContainsNoneOf([1, 2, 3])([1])
|
| 841 |
+
|
| 842 |
+
with pytest.raises(
|
| 843 |
+
ValidationError, match="One or more of the choices you made was in: one, two"
|
| 844 |
+
):
|
| 845 |
+
validate.ContainsNoneOf(["one", "two"])(["one"])
|
| 846 |
+
|
| 847 |
+
with pytest.raises(
|
| 848 |
+
ValidationError, match="One or more of the choices you made was in: @, !, &, ?"
|
| 849 |
+
):
|
| 850 |
+
validate.ContainsNoneOf("@!&?")("@")
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
def test_containsnoneof_in_list():
|
| 854 |
+
assert validate.ContainsNoneOf([])([]) == []
|
| 855 |
+
assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3]
|
| 856 |
+
assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3]
|
| 857 |
+
assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4]
|
| 858 |
+
assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4]
|
| 859 |
+
assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1]
|
| 860 |
+
|
| 861 |
+
with pytest.raises(ValidationError):
|
| 862 |
+
validate.ContainsNoneOf([1])([1, 2, 3])
|
| 863 |
+
|
| 864 |
+
with pytest.raises(ValidationError):
|
| 865 |
+
validate.ContainsNoneOf([1, 1, 1])([1, 2, 3])
|
| 866 |
+
|
| 867 |
+
with pytest.raises(ValidationError):
|
| 868 |
+
validate.ContainsNoneOf([1, 2])([1, 2])
|
| 869 |
+
|
| 870 |
+
with pytest.raises(ValidationError):
|
| 871 |
+
validate.ContainsNoneOf([1])([1, 1, 1, 1])
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def test_containsnoneof_unhashable_types():
|
| 875 |
+
assert validate.ContainsNoneOf([[1], [2], [3]])([]) == []
|
| 876 |
+
assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]]
|
| 877 |
+
assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]]
|
| 878 |
+
assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]]
|
| 879 |
+
|
| 880 |
+
with pytest.raises(ValidationError):
|
| 881 |
+
validate.ContainsNoneOf([[1], [2], [3]])([[1]])
|
| 882 |
+
|
| 883 |
+
with pytest.raises(ValidationError):
|
| 884 |
+
validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]])
|
| 885 |
+
|
| 886 |
+
with pytest.raises(ValidationError):
|
| 887 |
+
validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]])
|
| 888 |
+
|
| 889 |
+
with pytest.raises(ValidationError):
|
| 890 |
+
validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]])
|
| 891 |
+
|
| 892 |
+
with pytest.raises(ValidationError):
|
| 893 |
+
validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]])
|
| 894 |
+
|
| 895 |
+
with pytest.raises(ValidationError):
|
| 896 |
+
validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]])
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def test_containsnoneof_in_tuple():
|
| 900 |
+
assert validate.ContainsNoneOf(())(()) == ()
|
| 901 |
+
assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3)
|
| 902 |
+
assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3)
|
| 903 |
+
assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4)
|
| 904 |
+
assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,)
|
| 905 |
+
assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1)
|
| 906 |
+
|
| 907 |
+
with pytest.raises(ValidationError):
|
| 908 |
+
validate.ContainsNoneOf((1,))((1, 2, 3))
|
| 909 |
+
|
| 910 |
+
with pytest.raises(ValidationError):
|
| 911 |
+
validate.ContainsNoneOf((1, 1, 1))((1, 2, 3))
|
| 912 |
+
|
| 913 |
+
with pytest.raises(ValidationError):
|
| 914 |
+
validate.ContainsNoneOf((1, 2))((1, 2))
|
| 915 |
+
|
| 916 |
+
with pytest.raises(ValidationError):
|
| 917 |
+
validate.ContainsNoneOf((1,))((1, 1, 1, 1))
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
def test_containsnoneof_in_string():
|
| 921 |
+
assert validate.ContainsNoneOf("")("") == ""
|
| 922 |
+
assert validate.ContainsNoneOf("")("abc") == "abc"
|
| 923 |
+
assert validate.ContainsNoneOf("d")("abc") == "abc"
|
| 924 |
+
assert validate.ContainsNoneOf("b")("acd") == "acd"
|
| 925 |
+
assert validate.ContainsNoneOf("abc")("d") == "d"
|
| 926 |
+
assert validate.ContainsNoneOf("d")("aaaa") == "aaaa"
|
| 927 |
+
|
| 928 |
+
with pytest.raises(ValidationError):
|
| 929 |
+
validate.ContainsNoneOf("a")("abc")
|
| 930 |
+
|
| 931 |
+
with pytest.raises(ValidationError):
|
| 932 |
+
validate.ContainsNoneOf("aaa")("abc")
|
| 933 |
+
|
| 934 |
+
with pytest.raises(ValidationError):
|
| 935 |
+
validate.ContainsNoneOf("ab")("ab")
|
| 936 |
+
|
| 937 |
+
with pytest.raises(ValidationError):
|
| 938 |
+
validate.ContainsNoneOf("a")("aaaa")
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
def test_containsnoneof_custom_message():
|
| 942 |
+
validator = validate.ContainsNoneOf(
|
| 943 |
+
[1, 2, 3], error="{input} was in the banned list: {values}"
|
| 944 |
+
)
|
| 945 |
+
expected = "1 was in the banned list: 1, 2, 3"
|
| 946 |
+
with pytest.raises(ValidationError, match=expected):
|
| 947 |
+
validator([1])
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
def test_containsnoneof_mixing_types():
|
| 951 |
+
with pytest.raises(ValidationError):
|
| 952 |
+
validate.ContainsNoneOf("abc")(["a"])
|
| 953 |
+
|
| 954 |
+
with pytest.raises(ValidationError):
|
| 955 |
+
validate.ContainsNoneOf(["a", "b", "c"])("a")
|
| 956 |
+
|
| 957 |
+
with pytest.raises(ValidationError):
|
| 958 |
+
validate.ContainsNoneOf((1, 2, 3))([1])
|
| 959 |
+
|
| 960 |
+
with pytest.raises(ValidationError):
|
| 961 |
+
validate.ContainsNoneOf([1, 2, 3])((1,))
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
def is_even(value):
|
| 965 |
+
if value % 2 != 0:
|
| 966 |
+
raise ValidationError("Not an even value.")
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
def test_and():
|
| 970 |
+
validator = validate.And(validate.Range(min=0), is_even)
|
| 971 |
+
assert validator(2)
|
| 972 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 973 |
+
validator(-1)
|
| 974 |
+
errors = excinfo.value.messages
|
| 975 |
+
assert errors == ["Must be greater than or equal to 0.", "Not an even value."]
|
| 976 |
+
|
| 977 |
+
validator_with_composition = validate.And(validator, validate.Range(max=6))
|
| 978 |
+
assert validator_with_composition(4)
|
| 979 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 980 |
+
validator_with_composition(7)
|
| 981 |
+
|
| 982 |
+
errors = excinfo.value.messages
|
| 983 |
+
assert errors == ["Not an even value.", "Must be less than or equal to 6."]
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_version_attributes.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ruff: noqa: B018
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import marshmallow
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_version_attributes_deprecated():
|
| 8 |
+
with pytest.warns(DeprecationWarning):
|
| 9 |
+
marshmallow.__version__
|
| 10 |
+
|
| 11 |
+
with pytest.warns(DeprecationWarning):
|
| 12 |
+
marshmallow.__parsed_version__
|
| 13 |
+
|
| 14 |
+
with pytest.warns(DeprecationWarning):
|
| 15 |
+
marshmallow.__version_info__
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tox.ini
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[tox]
|
| 2 |
+
envlist = lint,mypy-test,py{39,310,311,312,313},docs
|
| 3 |
+
|
| 4 |
+
[testenv]
|
| 5 |
+
extras = tests
|
| 6 |
+
commands = pytest {posargs}
|
| 7 |
+
|
| 8 |
+
[testenv:lint]
|
| 9 |
+
deps = pre-commit~=3.5
|
| 10 |
+
skip_install = true
|
| 11 |
+
commands = pre-commit run --all-files
|
| 12 |
+
|
| 13 |
+
[testenv:mypy-test]
|
| 14 |
+
deps = mypy
|
| 15 |
+
commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/
|
| 16 |
+
|
| 17 |
+
[testenv:docs]
|
| 18 |
+
extras = docs
|
| 19 |
+
commands = sphinx-build docs/ docs/_build {posargs}
|
| 20 |
+
|
| 21 |
+
; Below tasks are for development only (not run in CI)
|
| 22 |
+
|
| 23 |
+
[testenv:watch-docs]
|
| 24 |
+
deps = sphinx-autobuild
|
| 25 |
+
extras = docs
|
| 26 |
+
commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2
|
| 27 |
+
|
| 28 |
+
[testenv:watch-readme]
|
| 29 |
+
deps = restview
|
| 30 |
+
skip_install = true
|
| 31 |
+
commands = restview README.rst
|
| 32 |
+
|
| 33 |
+
[testenv:benchmark]
|
| 34 |
+
usedevelop = true
|
| 35 |
+
commands = python performance/benchmark.py --iterations=100 --repeat=3
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/canaries/first-hunk-only.sh
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -Eeuo pipefail
|
| 3 |
+
cd /testbed/repo
|
| 4 |
+
cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL'
|
| 5 |
+
diff --git a/src/marshmallow/error_store.py b/src/marshmallow/error_store.py
|
| 6 |
+
index 419d43eaa143bf995a9e3b497369ab3a7a30282d..72b703736428168885ab02a800d8f755cc4d3bf6 100644
|
| 7 |
+
--- a/src/marshmallow/error_store.py
|
| 8 |
+
+++ b/src/marshmallow/error_store.py
|
| 9 |
+
@@ -15,11 +15,14 @@
|
| 10 |
+
self.errors = {}
|
| 11 |
+
|
| 12 |
+
def store_error(self, messages, field_name=SCHEMA, index=None):
|
| 13 |
+
- if field_name == SCHEMA and isinstance(messages, dict):
|
| 14 |
+
- messages = [messages]
|
| 15 |
+
- if index == 0:
|
| 16 |
+
+ # field error -> store/merge error messages under field name key
|
| 17 |
+
+ # schema error -> if string or list, store/merge under _schema key
|
| 18 |
+
+ # -> if dict, store/merge with other top-level keys
|
| 19 |
+
+ if field_name != SCHEMA or not isinstance(messages, dict):
|
| 20 |
+
messages = {field_name: messages}
|
| 21 |
+
- self.errors = merge_errors(messages, self.errors)
|
| 22 |
+
+ if index is not None:
|
| 23 |
+
+ messages = {index: messages}
|
| 24 |
+
+ self.errors = merge_errors(self.errors, messages)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def merge_errors(errors1, errors2):
|
| 28 |
+
OPENENV_PARTIAL
|
| 29 |
+
/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/canaries/original-bug.sh
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -Eeuo pipefail
|
| 3 |
+
:
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/openenv.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"canaries": "validation/canaries",
|
| 3 |
+
"profile": "harbor-semantic-v1",
|
| 4 |
+
"requires_credentials": false,
|
| 5 |
+
"resources": {
|
| 6 |
+
"cpu": 2,
|
| 7 |
+
"disk_mb": 16384,
|
| 8 |
+
"episode_timeout_s": 1800,
|
| 9 |
+
"memory_mb": 8192
|
| 10 |
+
},
|
| 11 |
+
"reward": {
|
| 12 |
+
"floor_margin": 0.1,
|
| 13 |
+
"oracle_tolerance": 0,
|
| 14 |
+
"range": [
|
| 15 |
+
0,
|
| 16 |
+
1
|
| 17 |
+
]
|
| 18 |
+
},
|
| 19 |
+
"reward_key": "reward",
|
| 20 |
+
"types": {
|
| 21 |
+
"tags": [
|
| 22 |
+
"swe",
|
| 23 |
+
"python",
|
| 24 |
+
"mutation-repair"
|
| 25 |
+
]
|
| 26 |
+
}
|
| 27 |
+
}
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/LICENSE.source
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright Steven Loria and contributors
|
| 2 |
+
|
| 3 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 4 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 5 |
+
in the Software without restriction, including without limitation the rights
|
| 6 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 7 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 8 |
+
furnished to do so, subject to the following conditions:
|
| 9 |
+
|
| 10 |
+
The above copyright notice and this permission notice shall be included in
|
| 11 |
+
all copies or substantial portions of the Software.
|
| 12 |
+
|
| 13 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 14 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 15 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 16 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 17 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 18 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 19 |
+
THE SOFTWARE.
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/adapter.json
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"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.",
|
| 3 |
+
"collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59",
|
| 4 |
+
"dependency_installation_pinned": false,
|
| 5 |
+
"dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2",
|
| 6 |
+
"gold_patch_sha256": "d2ab7394d572e23c97904cf70471c24c35009b73dce040ebfff8ceda350f30b8",
|
| 7 |
+
"hostile_code_isolation_established": false,
|
| 8 |
+
"known_wrong_semantic_implementations": 0,
|
| 9 |
+
"native_inventory_sha256": "eaa52c4db4ea58c622437d5befb7547b726810ea073054b3507c64eae4d6af4a",
|
| 10 |
+
"new_files_deletions_and_executable_modes_supported": true,
|
| 11 |
+
"official_profile": {
|
| 12 |
+
"eval_sets": [],
|
| 13 |
+
"profile_class": "Marshmallow9716fc62",
|
| 14 |
+
"profile_lines": [
|
| 15 |
+
542,
|
| 16 |
+
545
|
| 17 |
+
],
|
| 18 |
+
"profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f",
|
| 19 |
+
"profile_source_path": "swesmith/profiles/python.py",
|
| 20 |
+
"profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286",
|
| 21 |
+
"upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725",
|
| 22 |
+
"upstream_repo": "marshmallow-code/marshmallow"
|
| 23 |
+
},
|
| 24 |
+
"original_bug_canary_nop_equivalent": true,
|
| 25 |
+
"original_bug_runtime_wrongness_established": false,
|
| 26 |
+
"partial_repair_canary": true,
|
| 27 |
+
"partial_repair_sha256": "d78795aae0ce90809b13ed16ea2ab418ad91c855638e737c357dd2ea878b354f",
|
| 28 |
+
"partial_repair_wrongness_established": false,
|
| 29 |
+
"provided_original_bug_control": true,
|
| 30 |
+
"repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git",
|
| 31 |
+
"runtime_image": null,
|
| 32 |
+
"runtime_ready": false,
|
| 33 |
+
"runtime_recipe": {
|
| 34 |
+
"dependency_installation_pinned": false,
|
| 35 |
+
"official_install_cmds": [
|
| 36 |
+
"python -m pip install -e ."
|
| 37 |
+
],
|
| 38 |
+
"official_pytest_argv": [
|
| 39 |
+
"pytest",
|
| 40 |
+
"--disable-warnings",
|
| 41 |
+
"--color=no",
|
| 42 |
+
"--tb=no",
|
| 43 |
+
"--verbose"
|
| 44 |
+
],
|
| 45 |
+
"official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose",
|
| 46 |
+
"panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.",
|
| 47 |
+
"python_version": "3.10",
|
| 48 |
+
"source_bound_test_dependency_cmds": [
|
| 49 |
+
"python -m pip install -e '.[tests]'"
|
| 50 |
+
],
|
| 51 |
+
"test_dependency_source_sha256": {
|
| 52 |
+
"pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd",
|
| 53 |
+
"tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877"
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"runtime_resource_review_required": false,
|
| 57 |
+
"schema": "python-git-patch-jobs-v1",
|
| 58 |
+
"source_base_commit": "5a0745a294404e1538c74004a906777bc1bb8395",
|
| 59 |
+
"source_completion_sha256": "3affac2a48e264ace97e82cd4ffb6d8c7c80c3ff01fe78f3cf551e9b65479c75",
|
| 60 |
+
"source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876",
|
| 61 |
+
"source_pr_url": null,
|
| 62 |
+
"source_record": {
|
| 63 |
+
"anti_training_canary": false,
|
| 64 |
+
"anti_training_reviewed": true,
|
| 65 |
+
"candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj",
|
| 66 |
+
"cloud_launch_ready": false,
|
| 67 |
+
"eligibility": {
|
| 68 |
+
"reasons": [],
|
| 69 |
+
"semantic_nonoverlap_established": false,
|
| 70 |
+
"status": "eligible_for_controls",
|
| 71 |
+
"training_admissible": false,
|
| 72 |
+
"warnings": []
|
| 73 |
+
},
|
| 74 |
+
"healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3",
|
| 75 |
+
"instruction_sha256": "32dabd19844c79b576e2178cc05877ad4dabf48b3fab55dcc4a523675203f950",
|
| 76 |
+
"is_fork": true,
|
| 77 |
+
"learner_path": "tasks/a8f57446286292e84eae251f/learner",
|
| 78 |
+
"license_evidence": {
|
| 79 |
+
"source_code": {
|
| 80 |
+
"actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725",
|
| 81 |
+
"actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE",
|
| 82 |
+
"reviewed": true,
|
| 83 |
+
"sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001",
|
| 84 |
+
"spdx": "MIT",
|
| 85 |
+
"training_allowed": true,
|
| 86 |
+
"url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5a0745a294404e1538c74004a906777bc1bb8395/LICENSE"
|
| 87 |
+
},
|
| 88 |
+
"task_bundle": {
|
| 89 |
+
"reviewed": true,
|
| 90 |
+
"sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808",
|
| 91 |
+
"spdx": "MIT",
|
| 92 |
+
"training_allowed": true,
|
| 93 |
+
"url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md"
|
| 94 |
+
}
|
| 95 |
+
},
|
| 96 |
+
"original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725",
|
| 97 |
+
"patch_sha256": "1582a7735b96db97d76648ac51722a14ecdb3128dcd16d9242635c2f31754d13",
|
| 98 |
+
"provenance_path": "tasks/a8f57446286292e84eae251f/source-proof.json",
|
| 99 |
+
"repository_lineage": [
|
| 100 |
+
"swesmith/marshmallow-code__marshmallow.9716fc62",
|
| 101 |
+
"marshmallow-code/marshmallow"
|
| 102 |
+
],
|
| 103 |
+
"rfc008_complete": false,
|
| 104 |
+
"runtime_qualified": false,
|
| 105 |
+
"semantic_nonoverlap_established": false,
|
| 106 |
+
"source_commit": "5a0745a294404e1538c74004a906777bc1bb8395",
|
| 107 |
+
"source_dataset": "SWE-bench/SWE-smith-py",
|
| 108 |
+
"source_head_commit": "30f880ddd089e15fc943c57c51b6cfb18d2781e7",
|
| 109 |
+
"source_kind": "mutation",
|
| 110 |
+
"source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62",
|
| 111 |
+
"source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e",
|
| 112 |
+
"source_split": "train",
|
| 113 |
+
"target_model_calibrated": false,
|
| 114 |
+
"task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj",
|
| 115 |
+
"task_sha256": "9ff4532cb3a78a68a116dc7fc3fabebbdb578d28ad03e0e2502815b1fa7f622d",
|
| 116 |
+
"training_admissible": false,
|
| 117 |
+
"upstream_identity_reviewed": true,
|
| 118 |
+
"upstream_repo": "marshmallow-code/marshmallow",
|
| 119 |
+
"usage": "quarantine_only"
|
| 120 |
+
},
|
| 121 |
+
"source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62",
|
| 122 |
+
"symlink_submodule_changes_supported": false,
|
| 123 |
+
"task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj",
|
| 124 |
+
"transfer": "index-independent-worktree-to-Git-binary-patch",
|
| 125 |
+
"transfer_path": "/testbed/submission.patch",
|
| 126 |
+
"upstream_repo": "marshmallow-code/marshmallow"
|
| 127 |
+
}
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/dependency-setup.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -Eeuo pipefail
|
| 3 |
+
source /opt/miniconda3/bin/activate
|
| 4 |
+
conda activate testbed
|
| 5 |
+
cd /testbed/repo
|
| 6 |
+
python -c 'import sys; assert sys.version_info[:2] == (3, 10)'
|
| 7 |
+
python -m pip install -e .
|
| 8 |
+
python -m pip install -e '.[tests]'
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/environment/Dockerfile
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Runtime is selected only by an independently qualified immutable amd64 receipt.
|
| 2 |
+
FROM ubuntu:22.04
|
| 3 |
+
RUN false
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/instruction.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
URL validation fails with UnboundLocalError
|
| 2 |
+
|
| 3 |
+
#### Description
|
| 4 |
+
|
| 5 |
+
URL validation is broken and raises `UnboundLocalError: local variable 'key' referenced before assignment` when trying to validate any URL.
|
| 6 |
+
|
| 7 |
+
#### Steps/Code to Reproduce
|
| 8 |
+
|
| 9 |
+
```python
|
| 10 |
+
from marshmallow import validate
|
| 11 |
+
|
| 12 |
+
# This should work but raises UnboundLocalError
|
| 13 |
+
validator = validate.URL()
|
| 14 |
+
validator('http://example.org')
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
The error occurs for all URL validation scenarios:
|
| 18 |
+
|
| 19 |
+
```python
|
| 20 |
+
from marshmallow import validate
|
| 21 |
+
|
| 22 |
+
# All of these raise UnboundLocalError
|
| 23 |
+
validate.URL(relative=False)('http://example.org')
|
| 24 |
+
validate.URL(relative=True)('/foo/bar')
|
| 25 |
+
validate.URL(require_tld=False)('http://example')
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
#### Expected Behavior
|
| 29 |
+
|
| 30 |
+
URL validation should work normally and either return the valid URL or raise a ValidationError for invalid URLs.
|
| 31 |
+
|
| 32 |
+
#### Actual Behavior
|
| 33 |
+
|
| 34 |
+
```
|
| 35 |
+
UnboundLocalError: local variable 'key' referenced before assignment
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
This affects all URL validation functionality in the library.
|
| 39 |
+
|
| 40 |
+
## Environment
|
| 41 |
+
|
| 42 |
+
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 <tests>`. Don't install packages: the tests need nothing else, and the sandbox may have no network access.
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/metadata.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/provenance.json
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"generated_reference": false,
|
| 3 |
+
"healthy_reference_delta_sha256": "d2ab7394d572e23c97904cf70471c24c35009b73dce040ebfff8ceda350f30b8",
|
| 4 |
+
"native_pytest_ids_preserved": true,
|
| 5 |
+
"original_source_code_license": {
|
| 6 |
+
"actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725",
|
| 7 |
+
"actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE",
|
| 8 |
+
"reviewed": true,
|
| 9 |
+
"sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001",
|
| 10 |
+
"spdx": "MIT",
|
| 11 |
+
"training_allowed": true,
|
| 12 |
+
"url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5a0745a294404e1538c74004a906777bc1bb8395/LICENSE"
|
| 13 |
+
},
|
| 14 |
+
"provided_reference": true,
|
| 15 |
+
"qwen_calibrated": false,
|
| 16 |
+
"runtime_qualified": false,
|
| 17 |
+
"source_completion_sha256": "3affac2a48e264ace97e82cd4ffb6d8c7c80c3ff01fe78f3cf551e9b65479c75",
|
| 18 |
+
"source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876",
|
| 19 |
+
"source_proof_sha256": "4b69b13ddb8eff4c8a6c8ff5d5f293ff055aa62f617b223f59bb2a0718ca535f",
|
| 20 |
+
"source_record": {
|
| 21 |
+
"anti_training_canary": false,
|
| 22 |
+
"anti_training_reviewed": true,
|
| 23 |
+
"candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj",
|
| 24 |
+
"cloud_launch_ready": false,
|
| 25 |
+
"eligibility": {
|
| 26 |
+
"reasons": [],
|
| 27 |
+
"semantic_nonoverlap_established": false,
|
| 28 |
+
"status": "eligible_for_controls",
|
| 29 |
+
"training_admissible": false,
|
| 30 |
+
"warnings": []
|
| 31 |
+
},
|
| 32 |
+
"healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3",
|
| 33 |
+
"instruction_sha256": "32dabd19844c79b576e2178cc05877ad4dabf48b3fab55dcc4a523675203f950",
|
| 34 |
+
"is_fork": true,
|
| 35 |
+
"learner_path": "tasks/a8f57446286292e84eae251f/learner",
|
| 36 |
+
"license_evidence": {
|
| 37 |
+
"source_code": {
|
| 38 |
+
"actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725",
|
| 39 |
+
"actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE",
|
| 40 |
+
"reviewed": true,
|
| 41 |
+
"sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001",
|
| 42 |
+
"spdx": "MIT",
|
| 43 |
+
"training_allowed": true,
|
| 44 |
+
"url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5a0745a294404e1538c74004a906777bc1bb8395/LICENSE"
|
| 45 |
+
},
|
| 46 |
+
"task_bundle": {
|
| 47 |
+
"reviewed": true,
|
| 48 |
+
"sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808",
|
| 49 |
+
"spdx": "MIT",
|
| 50 |
+
"training_allowed": true,
|
| 51 |
+
"url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md"
|
| 52 |
+
}
|
| 53 |
+
},
|
| 54 |
+
"original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725",
|
| 55 |
+
"patch_sha256": "1582a7735b96db97d76648ac51722a14ecdb3128dcd16d9242635c2f31754d13",
|
| 56 |
+
"provenance_path": "tasks/a8f57446286292e84eae251f/source-proof.json",
|
| 57 |
+
"repository_lineage": [
|
| 58 |
+
"swesmith/marshmallow-code__marshmallow.9716fc62",
|
| 59 |
+
"marshmallow-code/marshmallow"
|
| 60 |
+
],
|
| 61 |
+
"rfc008_complete": false,
|
| 62 |
+
"runtime_qualified": false,
|
| 63 |
+
"semantic_nonoverlap_established": false,
|
| 64 |
+
"source_commit": "5a0745a294404e1538c74004a906777bc1bb8395",
|
| 65 |
+
"source_dataset": "SWE-bench/SWE-smith-py",
|
| 66 |
+
"source_head_commit": "30f880ddd089e15fc943c57c51b6cfb18d2781e7",
|
| 67 |
+
"source_kind": "mutation",
|
| 68 |
+
"source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62",
|
| 69 |
+
"source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e",
|
| 70 |
+
"source_split": "train",
|
| 71 |
+
"target_model_calibrated": false,
|
| 72 |
+
"task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj",
|
| 73 |
+
"task_sha256": "9ff4532cb3a78a68a116dc7fc3fabebbdb578d28ad03e0e2502815b1fa7f622d",
|
| 74 |
+
"training_admissible": false,
|
| 75 |
+
"upstream_identity_reviewed": true,
|
| 76 |
+
"upstream_repo": "marshmallow-code/marshmallow",
|
| 77 |
+
"usage": "quarantine_only"
|
| 78 |
+
},
|
| 79 |
+
"task_bundle_license": {
|
| 80 |
+
"reviewed": true,
|
| 81 |
+
"sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808",
|
| 82 |
+
"spdx": "MIT",
|
| 83 |
+
"training_allowed": true,
|
| 84 |
+
"url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md"
|
| 85 |
+
},
|
| 86 |
+
"training_admissible": false,
|
| 87 |
+
"trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91"
|
| 88 |
+
}
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/provided-gold.diff
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py
|
| 2 |
+
index 1ff1b0db351cf1554b8b1563be1ca3dc97d944e0..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644
|
| 3 |
+
--- a/src/marshmallow/class_registry.py
|
| 4 |
+
+++ b/src/marshmallow/class_registry.py
|
| 5 |
+
@@ -77,17 +77,18 @@
|
| 6 |
+
"""
|
| 7 |
+
try:
|
| 8 |
+
classes = _registry[classname]
|
| 9 |
+
- except KeyError:
|
| 10 |
+
+ except KeyError as error:
|
| 11 |
+
raise RegistryError(
|
| 12 |
+
f"Class with name {classname!r} was not found. You may need "
|
| 13 |
+
"to import the class."
|
| 14 |
+
- )
|
| 15 |
+
+ ) from error
|
| 16 |
+
if len(classes) > 1:
|
| 17 |
+
- if not all:
|
| 18 |
+
+ if all:
|
| 19 |
+
return _registry[classname]
|
| 20 |
+
raise RegistryError(
|
| 21 |
+
f"Multiple classes with name {classname!r} "
|
| 22 |
+
"were found. Please use the full, "
|
| 23 |
+
"module-qualified path."
|
| 24 |
+
)
|
| 25 |
+
- return classes[-1]
|
| 26 |
+
+ else:
|
| 27 |
+
+ return _registry[classname][0]
|
| 28 |
+
diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py
|
| 29 |
+
index ce2430180eeaf81ee3f6d01318957fe936d857d9..e4536d88c4d4481e82c21d8757436653e59577e5 100644
|
| 30 |
+
--- a/src/marshmallow/validate.py
|
| 31 |
+
+++ b/src/marshmallow/validate.py
|
| 32 |
+
@@ -163,13 +163,14 @@
|
| 33 |
+
def __call__(
|
| 34 |
+
self, relative: bool, absolute: bool, require_tld: bool
|
| 35 |
+
) -> typing.Pattern:
|
| 36 |
+
+ key = (relative, absolute, require_tld)
|
| 37 |
+
if key not in self._memoized:
|
| 38 |
+
self._memoized[key] = self._regex_generator(
|
| 39 |
+
relative, absolute, require_tld
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
return self._memoized[key]
|
| 43 |
+
- key = (relative, absolute, require_tld)
|
| 44 |
+
+
|
| 45 |
+
_regex = RegexMemoizer()
|
| 46 |
+
|
| 47 |
+
default_message = "Not a valid URL."
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/solution/solve.sh
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -Eeuo pipefail
|
| 3 |
+
cd /testbed/repo
|
| 4 |
+
cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE'
|
| 5 |
+
diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py
|
| 6 |
+
index 1ff1b0db351cf1554b8b1563be1ca3dc97d944e0..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644
|
| 7 |
+
--- a/src/marshmallow/class_registry.py
|
| 8 |
+
+++ b/src/marshmallow/class_registry.py
|
| 9 |
+
@@ -77,17 +77,18 @@
|
| 10 |
+
"""
|
| 11 |
+
try:
|
| 12 |
+
classes = _registry[classname]
|
| 13 |
+
- except KeyError:
|
| 14 |
+
+ except KeyError as error:
|
| 15 |
+
raise RegistryError(
|
| 16 |
+
f"Class with name {classname!r} was not found. You may need "
|
| 17 |
+
"to import the class."
|
| 18 |
+
- )
|
| 19 |
+
+ ) from error
|
| 20 |
+
if len(classes) > 1:
|
| 21 |
+
- if not all:
|
| 22 |
+
+ if all:
|
| 23 |
+
return _registry[classname]
|
| 24 |
+
raise RegistryError(
|
| 25 |
+
f"Multiple classes with name {classname!r} "
|
| 26 |
+
"were found. Please use the full, "
|
| 27 |
+
"module-qualified path."
|
| 28 |
+
)
|
| 29 |
+
- return classes[-1]
|
| 30 |
+
+ else:
|
| 31 |
+
+ return _registry[classname][0]
|
| 32 |
+
diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py
|
| 33 |
+
index ce2430180eeaf81ee3f6d01318957fe936d857d9..e4536d88c4d4481e82c21d8757436653e59577e5 100644
|
| 34 |
+
--- a/src/marshmallow/validate.py
|
| 35 |
+
+++ b/src/marshmallow/validate.py
|
| 36 |
+
@@ -163,13 +163,14 @@
|
| 37 |
+
def __call__(
|
| 38 |
+
self, relative: bool, absolute: bool, require_tld: bool
|
| 39 |
+
) -> typing.Pattern:
|
| 40 |
+
+ key = (relative, absolute, require_tld)
|
| 41 |
+
if key not in self._memoized:
|
| 42 |
+
self._memoized[key] = self._regex_generator(
|
| 43 |
+
relative, absolute, require_tld
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
return self._memoized[key]
|
| 47 |
+
- key = (relative, absolute, require_tld)
|
| 48 |
+
+
|
| 49 |
+
_regex = RegexMemoizer()
|
| 50 |
+
|
| 51 |
+
default_message = "Not a valid URL."
|
| 52 |
+
OPENENV_REFERENCE
|
| 53 |
+
/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/task.toml
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
|
| 3 |
+
[agent]
|
| 4 |
+
timeout_sec = 1800.0
|
| 5 |
+
|
| 6 |
+
[verifier]
|
| 7 |
+
timeout_sec = 900.0
|
| 8 |
+
|
| 9 |
+
[environment]
|
| 10 |
+
docker_image = "ghcr.io/younesbelkada/scale800@sha256:ab70e635aa170a8051895226654b82557a5125f5aa0de1d671c45d7427e45ad3"
|
| 11 |
+
build_timeout_sec = 600.0
|
| 12 |
+
cpus = 2
|
| 13 |
+
memory_mb = 8192
|
| 14 |
+
storage_mb = 16384
|
| 15 |
+
|
| 16 |
+
[metadata]
|
| 17 |
+
author_name = "SWE-smith source adapter"
|
| 18 |
+
category = "bugfix"
|
| 19 |
+
tags = ["swe", "python", "mutation-repair"]
|
| 20 |
+
|
| 21 |
+
[environment.env]
|
| 22 |
+
# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's
|
| 23 |
+
# non-interactive shells never run `conda activate`
|
| 24 |
+
PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/check_pytest.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Preserve confirmed requested assertion failures; keep positive checks strict."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
import xml.etree.ElementTree as ET
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
GROUPS = ("pass-to-pass", "fail-to-pass")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def split_nodeid(target):
|
| 14 |
+
prefix, bracket, parameter = target.partition("[")
|
| 15 |
+
parts = prefix.split("::")
|
| 16 |
+
if bracket:
|
| 17 |
+
parts[-1] += bracket + parameter
|
| 18 |
+
return parts
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def matches(case, target):
|
| 22 |
+
parts = split_nodeid(target)
|
| 23 |
+
module = parts[0].removesuffix(".py").replace("/", ".")
|
| 24 |
+
classname, name = case.get("classname", ""), case.get("name", "")
|
| 25 |
+
if not (classname == module or classname.startswith(module + ".")):
|
| 26 |
+
return False
|
| 27 |
+
selector = parts[-1] if len(parts) > 1 else ""
|
| 28 |
+
classes = parts[1:-1]
|
| 29 |
+
if classes and classname != module + "." + ".".join(classes):
|
| 30 |
+
return False
|
| 31 |
+
return (
|
| 32 |
+
not selector
|
| 33 |
+
or name == selector
|
| 34 |
+
or ("[" not in selector and name.startswith(selector + "["))
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def capture_panels(root):
|
| 39 |
+
panels, digests = {}, {}
|
| 40 |
+
for group in GROUPS:
|
| 41 |
+
path = Path(root) / (group + ".xml")
|
| 42 |
+
if not path.exists():
|
| 43 |
+
panels[group] = None
|
| 44 |
+
continue
|
| 45 |
+
with path.open("rb") as stream:
|
| 46 |
+
raw = stream.read(4 * 1024**2 + 1)
|
| 47 |
+
if not 0 < len(raw) <= 4 * 1024**2 or re.search(
|
| 48 |
+
rb"<!\s*(?:DOCTYPE|ENTITY)", raw, re.I
|
| 49 |
+
):
|
| 50 |
+
raise ValueError("Unbounded or unsafe pytest XML")
|
| 51 |
+
try:
|
| 52 |
+
tree = ET.fromstring(raw)
|
| 53 |
+
except ET.ParseError:
|
| 54 |
+
raise ValueError("Malformed pytest XML") from None
|
| 55 |
+
cases = list(tree.iter("testcase"))
|
| 56 |
+
if len(cases) > 20000:
|
| 57 |
+
raise ValueError("Too many pytest cases")
|
| 58 |
+
identities = [(case.get("classname"), case.get("name")) for case in cases]
|
| 59 |
+
if len(identities) != len(set(identities)):
|
| 60 |
+
raise ValueError("Duplicate pytest case evidence")
|
| 61 |
+
panels[group] = cases
|
| 62 |
+
digests[group] = hashlib.sha256(raw).hexdigest()
|
| 63 |
+
return panels, digests
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def strict_assess(panels, expected, native_exit):
|
| 67 |
+
"""The original positive-approval conditions, applied to captured cases."""
|
| 68 |
+
all_cases, actual_failure = [], False
|
| 69 |
+
for group in GROUPS:
|
| 70 |
+
cases = panels[group]
|
| 71 |
+
if cases is None:
|
| 72 |
+
if actual_failure:
|
| 73 |
+
continue
|
| 74 |
+
raise ValueError("Missing preceding pytest panel")
|
| 75 |
+
if actual_failure:
|
| 76 |
+
raise ValueError(
|
| 77 |
+
"Pytest evidence continued after the native stop-on-failure"
|
| 78 |
+
)
|
| 79 |
+
targets = expected[group]
|
| 80 |
+
if any(not any(matches(case, target) for target in targets) for case in cases):
|
| 81 |
+
raise ValueError("Unexpected pytest case")
|
| 82 |
+
all_cases.extend(cases)
|
| 83 |
+
failures = [case for case in cases if case.find("failure") is not None]
|
| 84 |
+
if any(
|
| 85 |
+
case.find("error") is not None or case.find("skipped") is not None
|
| 86 |
+
for case in cases
|
| 87 |
+
):
|
| 88 |
+
raise ValueError("Pytest collection/error/skip is not a completed panel")
|
| 89 |
+
actual_failure = actual_failure or bool(failures)
|
| 90 |
+
if not failures and any(
|
| 91 |
+
not any(matches(case, target) for case in cases) for target in targets
|
| 92 |
+
):
|
| 93 |
+
raise ValueError("Declared pytest target never ran")
|
| 94 |
+
if actual_failure:
|
| 95 |
+
if native_exit == 0:
|
| 96 |
+
raise ValueError("Native verifier exit disagrees with pytest failure")
|
| 97 |
+
return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)}
|
| 98 |
+
if native_exit != 0:
|
| 99 |
+
raise ValueError("Setup or native verifier failed without a real test failure")
|
| 100 |
+
if any(panels[group] is None for group in GROUPS):
|
| 101 |
+
raise ValueError("Missing completed pytest panel")
|
| 102 |
+
return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def assess(root, expected, native_exit):
|
| 106 |
+
if type(native_exit) is not int:
|
| 107 |
+
raise ValueError("Native verifier exit must be an integer")
|
| 108 |
+
if not isinstance(expected, dict) or any(
|
| 109 |
+
not isinstance(expected.get(group), list)
|
| 110 |
+
or not expected[group]
|
| 111 |
+
or any(not isinstance(target, str) or not target for target in expected[group])
|
| 112 |
+
for group in GROUPS
|
| 113 |
+
):
|
| 114 |
+
raise ValueError("Complete exact native pytest targets required")
|
| 115 |
+
panels, digests = capture_panels(root)
|
| 116 |
+
counts = {
|
| 117 |
+
"cases": 0,
|
| 118 |
+
"matched_failures": 0,
|
| 119 |
+
"unexpected_cases": 0,
|
| 120 |
+
"unmatched_failures": 0,
|
| 121 |
+
"skipped_cases": 0,
|
| 122 |
+
"error_cases": 0,
|
| 123 |
+
"missing_panels": 0,
|
| 124 |
+
"missing_targets": 0,
|
| 125 |
+
}
|
| 126 |
+
for group in GROUPS:
|
| 127 |
+
cases = panels[group]
|
| 128 |
+
if cases is None:
|
| 129 |
+
counts["missing_panels"] += 1
|
| 130 |
+
counts["missing_targets"] += len(expected[group])
|
| 131 |
+
continue
|
| 132 |
+
counts["cases"] += len(cases)
|
| 133 |
+
for case in cases:
|
| 134 |
+
requested = any(matches(case, target) for target in expected[group])
|
| 135 |
+
failure = case.find("failure") is not None
|
| 136 |
+
counts["matched_failures"] += int(requested and failure)
|
| 137 |
+
counts["unmatched_failures"] += int(not requested and failure)
|
| 138 |
+
counts["unexpected_cases"] += int(not requested)
|
| 139 |
+
counts["skipped_cases"] += int(case.find("skipped") is not None)
|
| 140 |
+
counts["error_cases"] += int(case.find("error") is not None)
|
| 141 |
+
counts["missing_targets"] += sum(
|
| 142 |
+
not any(matches(case, target) for case in cases)
|
| 143 |
+
for target in expected[group]
|
| 144 |
+
)
|
| 145 |
+
if counts["matched_failures"]:
|
| 146 |
+
if native_exit == 0:
|
| 147 |
+
raise ValueError(
|
| 148 |
+
"Native verifier exit disagrees with requested pytest failure"
|
| 149 |
+
)
|
| 150 |
+
return {
|
| 151 |
+
"reward": 0,
|
| 152 |
+
"valid_test_failure": True,
|
| 153 |
+
"cases": counts["cases"],
|
| 154 |
+
"diagnostic_counts": counts,
|
| 155 |
+
"panel_sha256": digests,
|
| 156 |
+
"decision": "confirmed_requested_failure_precedence",
|
| 157 |
+
}
|
| 158 |
+
result = strict_assess(panels, expected, native_exit)
|
| 159 |
+
result.update(diagnostic_counts=counts, panel_sha256=digests)
|
| 160 |
+
return result
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
if __name__ == "__main__":
|
| 164 |
+
parser = argparse.ArgumentParser()
|
| 165 |
+
parser.add_argument("--root", required=True)
|
| 166 |
+
parser.add_argument("--expected", required=True)
|
| 167 |
+
parser.add_argument("--native-exit", type=int, required=True)
|
| 168 |
+
args = parser.parse_args()
|
| 169 |
+
result = assess(
|
| 170 |
+
args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit
|
| 171 |
+
)
|
| 172 |
+
reward = Path(args.root) / "reward.txt"
|
| 173 |
+
if reward.read_text().strip() != str(result["reward"]):
|
| 174 |
+
raise ValueError("Native raw reward disagrees with pytest evidence")
|
| 175 |
+
(Path(args.root) / "pytest-evidence.json").write_text(
|
| 176 |
+
json.dumps(result, sort_keys=True) + "\n"
|
| 177 |
+
)
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/expected-panels.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/grade.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trusted private pytest panel runner. Installed only in a fresh grader Job."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
| 8 |
+
import stat
|
| 9 |
+
import subprocess
|
| 10 |
+
from pathlib import Path, PurePosixPath
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def sha(raw):
|
| 14 |
+
return hashlib.sha256(raw).hexdigest()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def safe(value):
|
| 18 |
+
path = PurePosixPath(value)
|
| 19 |
+
if (
|
| 20 |
+
path.is_absolute()
|
| 21 |
+
or path.as_posix() != value
|
| 22 |
+
or not path.parts
|
| 23 |
+
or any(part in {".", "..", ".git"} for part in path.parts)
|
| 24 |
+
):
|
| 25 |
+
raise ValueError("Unsafe trusted test path")
|
| 26 |
+
return path
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def restore(worktree, private, manifest):
|
| 30 |
+
worktree, private = Path(worktree), Path(private)
|
| 31 |
+
captured = {}
|
| 32 |
+
for name, expected in manifest["files"].items():
|
| 33 |
+
path = private / safe(name)
|
| 34 |
+
info = path.lstat()
|
| 35 |
+
raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b""
|
| 36 |
+
if (
|
| 37 |
+
not stat.S_ISREG(info.st_mode)
|
| 38 |
+
or len(raw) != expected["bytes"]
|
| 39 |
+
or sha(raw) != expected["sha256"]
|
| 40 |
+
or stat.S_IMODE(info.st_mode) != expected["mode"]
|
| 41 |
+
):
|
| 42 |
+
raise ValueError("Trusted private test bytes or modes drifted")
|
| 43 |
+
captured[name] = (raw, expected["mode"])
|
| 44 |
+
# Capture and verify every private byte before changing the submitted tree.
|
| 45 |
+
for name in manifest["directory_roots"]:
|
| 46 |
+
destination = worktree / safe(name)
|
| 47 |
+
if destination.is_symlink():
|
| 48 |
+
raise ValueError("Submitted test directory is a symlink")
|
| 49 |
+
for parent in destination.parents:
|
| 50 |
+
if parent == worktree:
|
| 51 |
+
break
|
| 52 |
+
if parent.is_symlink():
|
| 53 |
+
raise ValueError("Submitted test parent is a symlink")
|
| 54 |
+
if destination.exists():
|
| 55 |
+
if not destination.is_dir():
|
| 56 |
+
raise ValueError("Submitted test directory is not a directory")
|
| 57 |
+
shutil.rmtree(destination)
|
| 58 |
+
for name, (raw, mode) in captured.items():
|
| 59 |
+
destination = worktree / safe(name)
|
| 60 |
+
for parent in destination.parents:
|
| 61 |
+
if parent == worktree:
|
| 62 |
+
break
|
| 63 |
+
if parent.is_symlink():
|
| 64 |
+
raise ValueError("Submitted test parent is a symlink")
|
| 65 |
+
if destination.is_symlink():
|
| 66 |
+
raise ValueError("Submitted trusted file is a symlink")
|
| 67 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
destination.write_bytes(raw)
|
| 69 |
+
destination.chmod(mode)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def run(worktree, private_root, output, invoke=None):
|
| 73 |
+
private_root, output, worktree = Path(private_root), Path(output), Path(worktree)
|
| 74 |
+
expected = json.loads((private_root / "expected-panels.json").read_bytes())
|
| 75 |
+
config = json.loads((private_root / "panel-config.json").read_bytes())
|
| 76 |
+
manifest = json.loads((private_root / "trusted-inventory.json").read_bytes())
|
| 77 |
+
restore(worktree, private_root / "trusted", manifest)
|
| 78 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 79 |
+
for name in (
|
| 80 |
+
"reward.txt",
|
| 81 |
+
"pass-to-pass.xml",
|
| 82 |
+
"fail-to-pass.xml",
|
| 83 |
+
"pytest-evidence.json",
|
| 84 |
+
):
|
| 85 |
+
(output / name).unlink(missing_ok=True)
|
| 86 |
+
environment = dict(os.environ)
|
| 87 |
+
for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"):
|
| 88 |
+
environment.pop(key, None)
|
| 89 |
+
commands, native_exit = [], 0
|
| 90 |
+
invoke = invoke or subprocess.run
|
| 91 |
+
for group in ("pass-to-pass", "fail-to-pass"):
|
| 92 |
+
if (
|
| 93 |
+
not isinstance(expected[group], list)
|
| 94 |
+
or not expected[group]
|
| 95 |
+
or any(
|
| 96 |
+
not isinstance(target, str) or not target for target in expected[group]
|
| 97 |
+
)
|
| 98 |
+
):
|
| 99 |
+
raise ValueError("Frozen native pytest selectors are incomplete")
|
| 100 |
+
command = [
|
| 101 |
+
*config["official_pytest_argv"],
|
| 102 |
+
"--override-ini=addopts=",
|
| 103 |
+
"--junitxml=" + str(output / (group + ".xml")),
|
| 104 |
+
*expected[group],
|
| 105 |
+
]
|
| 106 |
+
result = invoke(command, cwd=worktree, env=environment, check=False)
|
| 107 |
+
native_exit = result.returncode
|
| 108 |
+
commands.append({"group": group, "argv": command, "exit_code": native_exit})
|
| 109 |
+
if native_exit != 0:
|
| 110 |
+
break
|
| 111 |
+
(output / "pytest-commands.json").write_text(
|
| 112 |
+
json.dumps(commands, sort_keys=True) + "\n"
|
| 113 |
+
)
|
| 114 |
+
spec = importlib.util.spec_from_file_location(
|
| 115 |
+
"trusted_pytest_result", private_root / "check_pytest.py"
|
| 116 |
+
)
|
| 117 |
+
checker = importlib.util.module_from_spec(spec)
|
| 118 |
+
spec.loader.exec_module(checker)
|
| 119 |
+
result = checker.assess(output, expected, native_exit)
|
| 120 |
+
(output / "reward.txt").write_text(str(result["reward"]) + "\n")
|
| 121 |
+
(output / "pytest-evidence.json").write_text(
|
| 122 |
+
json.dumps(result, sort_keys=True) + "\n"
|
| 123 |
+
)
|
| 124 |
+
return result
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
if __name__ == "__main__":
|
| 128 |
+
run("/testbed/repo", "/tests", "/logs/verifier")
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/panel-config.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"dependency_installation_pinned": false,
|
| 3 |
+
"official_install_cmds": [
|
| 4 |
+
"python -m pip install -e ."
|
| 5 |
+
],
|
| 6 |
+
"official_pytest_argv": [
|
| 7 |
+
"pytest",
|
| 8 |
+
"--disable-warnings",
|
| 9 |
+
"--color=no",
|
| 10 |
+
"--tb=no",
|
| 11 |
+
"--verbose"
|
| 12 |
+
],
|
| 13 |
+
"official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose",
|
| 14 |
+
"panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.",
|
| 15 |
+
"python_version": "3.10",
|
| 16 |
+
"source_bound_test_dependency_cmds": [
|
| 17 |
+
"python -m pip install -e '.[tests]'"
|
| 18 |
+
],
|
| 19 |
+
"test_dependency_source_sha256": {
|
| 20 |
+
"pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd",
|
| 21 |
+
"tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877"
|
| 22 |
+
}
|
| 23 |
+
}
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/test.sh
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -Eeuo pipefail
|
| 3 |
+
source /opt/miniconda3/bin/activate
|
| 4 |
+
conda activate testbed
|
| 5 |
+
cd /testbed/repo
|
| 6 |
+
exec python -I /tests/grade.py
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted-inventory.json
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"directory_roots": [
|
| 3 |
+
"tests"
|
| 4 |
+
],
|
| 5 |
+
"files": {
|
| 6 |
+
"pyproject.toml": {
|
| 7 |
+
"bytes": 2514,
|
| 8 |
+
"mode": 420,
|
| 9 |
+
"sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd"
|
| 10 |
+
},
|
| 11 |
+
"tests/__init__.py": {
|
| 12 |
+
"bytes": 0,
|
| 13 |
+
"mode": 420,
|
| 14 |
+
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
| 15 |
+
},
|
| 16 |
+
"tests/base.py": {
|
| 17 |
+
"bytes": 8963,
|
| 18 |
+
"mode": 420,
|
| 19 |
+
"sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3"
|
| 20 |
+
},
|
| 21 |
+
"tests/conftest.py": {
|
| 22 |
+
"bytes": 566,
|
| 23 |
+
"mode": 420,
|
| 24 |
+
"sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057"
|
| 25 |
+
},
|
| 26 |
+
"tests/foo_serializer.py": {
|
| 27 |
+
"bytes": 97,
|
| 28 |
+
"mode": 420,
|
| 29 |
+
"sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91"
|
| 30 |
+
},
|
| 31 |
+
"tests/mypy_test_cases/test_validation_error.py": {
|
| 32 |
+
"bytes": 579,
|
| 33 |
+
"mode": 420,
|
| 34 |
+
"sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab"
|
| 35 |
+
},
|
| 36 |
+
"tests/test_decorators.py": {
|
| 37 |
+
"bytes": 30937,
|
| 38 |
+
"mode": 420,
|
| 39 |
+
"sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5"
|
| 40 |
+
},
|
| 41 |
+
"tests/test_deserialization.py": {
|
| 42 |
+
"bytes": 88128,
|
| 43 |
+
"mode": 420,
|
| 44 |
+
"sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2"
|
| 45 |
+
},
|
| 46 |
+
"tests/test_error_store.py": {
|
| 47 |
+
"bytes": 5137,
|
| 48 |
+
"mode": 420,
|
| 49 |
+
"sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f"
|
| 50 |
+
},
|
| 51 |
+
"tests/test_exceptions.py": {
|
| 52 |
+
"bytes": 1416,
|
| 53 |
+
"mode": 420,
|
| 54 |
+
"sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77"
|
| 55 |
+
},
|
| 56 |
+
"tests/test_fields.py": {
|
| 57 |
+
"bytes": 24578,
|
| 58 |
+
"mode": 420,
|
| 59 |
+
"sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf"
|
| 60 |
+
},
|
| 61 |
+
"tests/test_options.py": {
|
| 62 |
+
"bytes": 7852,
|
| 63 |
+
"mode": 420,
|
| 64 |
+
"sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de"
|
| 65 |
+
},
|
| 66 |
+
"tests/test_registry.py": {
|
| 67 |
+
"bytes": 6907,
|
| 68 |
+
"mode": 420,
|
| 69 |
+
"sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e"
|
| 70 |
+
},
|
| 71 |
+
"tests/test_schema.py": {
|
| 72 |
+
"bytes": 92822,
|
| 73 |
+
"mode": 420,
|
| 74 |
+
"sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f"
|
| 75 |
+
},
|
| 76 |
+
"tests/test_serialization.py": {
|
| 77 |
+
"bytes": 39066,
|
| 78 |
+
"mode": 420,
|
| 79 |
+
"sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f"
|
| 80 |
+
},
|
| 81 |
+
"tests/test_utils.py": {
|
| 82 |
+
"bytes": 7716,
|
| 83 |
+
"mode": 420,
|
| 84 |
+
"sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59"
|
| 85 |
+
},
|
| 86 |
+
"tests/test_validate.py": {
|
| 87 |
+
"bytes": 32663,
|
| 88 |
+
"mode": 420,
|
| 89 |
+
"sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd"
|
| 90 |
+
},
|
| 91 |
+
"tests/test_version_attributes.py": {
|
| 92 |
+
"bytes": 336,
|
| 93 |
+
"mode": 420,
|
| 94 |
+
"sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345"
|
| 95 |
+
},
|
| 96 |
+
"tox.ini": {
|
| 97 |
+
"bytes": 827,
|
| 98 |
+
"mode": 420,
|
| 99 |
+
"sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877"
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
}
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/pyproject.toml
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "marshmallow"
|
| 3 |
+
version = "3.23.1"
|
| 4 |
+
description = "A lightweight library for converting complex datatypes to and from native Python datatypes."
|
| 5 |
+
readme = "README.rst"
|
| 6 |
+
license = { file = "LICENSE" }
|
| 7 |
+
authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }]
|
| 8 |
+
maintainers = [
|
| 9 |
+
{ name = "Steven Loria", email = "sloria1@gmail.com" },
|
| 10 |
+
{ name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" },
|
| 11 |
+
{ name = "Jared Deckard", email = "jared@shademaps.com" },
|
| 12 |
+
]
|
| 13 |
+
classifiers = [
|
| 14 |
+
"Development Status :: 5 - Production/Stable",
|
| 15 |
+
"Intended Audience :: Developers",
|
| 16 |
+
"License :: OSI Approved :: MIT License",
|
| 17 |
+
"Programming Language :: Python :: 3",
|
| 18 |
+
"Programming Language :: Python :: 3.9",
|
| 19 |
+
"Programming Language :: Python :: 3.10",
|
| 20 |
+
"Programming Language :: Python :: 3.11",
|
| 21 |
+
"Programming Language :: Python :: 3.12",
|
| 22 |
+
"Programming Language :: Python :: 3.13",
|
| 23 |
+
]
|
| 24 |
+
requires-python = ">=3.9"
|
| 25 |
+
dependencies = ["packaging>=17.0"]
|
| 26 |
+
|
| 27 |
+
[project.urls]
|
| 28 |
+
Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html"
|
| 29 |
+
Funding = "https://opencollective.com/marshmallow"
|
| 30 |
+
Issues = "https://github.com/marshmallow-code/marshmallow/issues"
|
| 31 |
+
Source = "https://github.com/marshmallow-code/marshmallow"
|
| 32 |
+
Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi"
|
| 33 |
+
|
| 34 |
+
[project.optional-dependencies]
|
| 35 |
+
docs = [
|
| 36 |
+
"sphinx==8.1.3",
|
| 37 |
+
"sphinx-issues==5.0.0",
|
| 38 |
+
"alabaster==1.0.0",
|
| 39 |
+
"sphinx-version-warning==1.1.2",
|
| 40 |
+
"autodocsumm==0.2.14",
|
| 41 |
+
]
|
| 42 |
+
tests = ["pytest", "simplejson"]
|
| 43 |
+
dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"]
|
| 44 |
+
|
| 45 |
+
[build-system]
|
| 46 |
+
requires = ["flit_core<4"]
|
| 47 |
+
build-backend = "flit_core.buildapi"
|
| 48 |
+
|
| 49 |
+
[tool.flit.sdist]
|
| 50 |
+
include = [
|
| 51 |
+
"docs/",
|
| 52 |
+
"tests/",
|
| 53 |
+
"CHANGELOG.rst",
|
| 54 |
+
"CONTRIBUTING.rst",
|
| 55 |
+
"SECURITY.md",
|
| 56 |
+
"NOTICE",
|
| 57 |
+
"tox.ini",
|
| 58 |
+
]
|
| 59 |
+
exclude = ["docs/_build/"]
|
| 60 |
+
|
| 61 |
+
[tool.ruff]
|
| 62 |
+
src = ["src"]
|
| 63 |
+
fix = true
|
| 64 |
+
show-fixes = true
|
| 65 |
+
output-format = "full"
|
| 66 |
+
|
| 67 |
+
[tool.ruff.format]
|
| 68 |
+
docstring-code-format = true
|
| 69 |
+
|
| 70 |
+
[tool.ruff.lint]
|
| 71 |
+
ignore = ["E203", "E266", "E501", "E731"]
|
| 72 |
+
select = [
|
| 73 |
+
"B", # flake8-bugbear
|
| 74 |
+
"E", # pycodestyle error
|
| 75 |
+
"F", # pyflakes
|
| 76 |
+
"I", # isort
|
| 77 |
+
"UP", # pyupgrade
|
| 78 |
+
"W", # pycodestyle warning
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
[tool.ruff.lint.per-file-ignores]
|
| 82 |
+
"tests/*" = ["E721"]
|
| 83 |
+
|
| 84 |
+
[tool.mypy]
|
| 85 |
+
ignore_missing_imports = true
|
| 86 |
+
warn_unreachable = true
|
| 87 |
+
warn_unused_ignores = true
|
| 88 |
+
warn_redundant_casts = true
|
| 89 |
+
no_implicit_optional = true
|
| 90 |
+
|
| 91 |
+
[tool.pytest.ini_options]
|
| 92 |
+
norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases"
|
| 93 |
+
addopts = "-v --tb=short"
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/__init__.py
ADDED
|
File without changes
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/base.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test utilities and fixtures."""
|
| 2 |
+
|
| 3 |
+
import datetime as dt
|
| 4 |
+
import functools
|
| 5 |
+
import uuid
|
| 6 |
+
from enum import Enum, IntEnum
|
| 7 |
+
from zoneinfo import ZoneInfo
|
| 8 |
+
|
| 9 |
+
import simplejson
|
| 10 |
+
|
| 11 |
+
from marshmallow import Schema, fields, missing, post_load, validate
|
| 12 |
+
from marshmallow.exceptions import ValidationError
|
| 13 |
+
|
| 14 |
+
central = ZoneInfo("America/Chicago")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class GenderEnum(IntEnum):
|
| 18 |
+
male = 1
|
| 19 |
+
female = 2
|
| 20 |
+
non_binary = 3
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class HairColorEnum(Enum):
|
| 24 |
+
black = "black hair"
|
| 25 |
+
brown = "brown hair"
|
| 26 |
+
blond = "blond hair"
|
| 27 |
+
red = "red hair"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DateEnum(Enum):
|
| 31 |
+
date_1 = dt.date(2004, 2, 29)
|
| 32 |
+
date_2 = dt.date(2008, 2, 29)
|
| 33 |
+
date_3 = dt.date(2012, 2, 29)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
ALL_FIELDS = [
|
| 37 |
+
fields.String,
|
| 38 |
+
fields.Integer,
|
| 39 |
+
fields.Boolean,
|
| 40 |
+
fields.Float,
|
| 41 |
+
fields.Number,
|
| 42 |
+
fields.DateTime,
|
| 43 |
+
fields.Time,
|
| 44 |
+
fields.Date,
|
| 45 |
+
fields.TimeDelta,
|
| 46 |
+
fields.Dict,
|
| 47 |
+
fields.Url,
|
| 48 |
+
fields.Email,
|
| 49 |
+
fields.UUID,
|
| 50 |
+
fields.Decimal,
|
| 51 |
+
fields.IP,
|
| 52 |
+
fields.IPv4,
|
| 53 |
+
fields.IPv6,
|
| 54 |
+
fields.IPInterface,
|
| 55 |
+
fields.IPv4Interface,
|
| 56 |
+
fields.IPv6Interface,
|
| 57 |
+
functools.partial(fields.Enum, GenderEnum),
|
| 58 |
+
functools.partial(fields.Enum, HairColorEnum, by_value=fields.String),
|
| 59 |
+
functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer),
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
##### Custom asserts #####
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def assert_date_equal(d1, d2):
|
| 67 |
+
assert d1.year == d2.year
|
| 68 |
+
assert d1.month == d2.month
|
| 69 |
+
assert d1.day == d2.day
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def assert_time_equal(t1, t2):
|
| 73 |
+
assert t1.hour == t2.hour
|
| 74 |
+
assert t1.minute == t2.minute
|
| 75 |
+
assert t1.second == t2.second
|
| 76 |
+
assert t1.microsecond == t2.microsecond
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
##### Models #####
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class User:
|
| 83 |
+
SPECIES = "Homo sapiens"
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
name,
|
| 88 |
+
age=0,
|
| 89 |
+
id_=None,
|
| 90 |
+
homepage=None,
|
| 91 |
+
email=None,
|
| 92 |
+
registered=True,
|
| 93 |
+
time_registered=None,
|
| 94 |
+
birthdate=None,
|
| 95 |
+
birthtime=None,
|
| 96 |
+
balance=100,
|
| 97 |
+
sex=GenderEnum.male,
|
| 98 |
+
hair_color=HairColorEnum.black,
|
| 99 |
+
employer=None,
|
| 100 |
+
various_data=None,
|
| 101 |
+
):
|
| 102 |
+
self.name = name
|
| 103 |
+
self.age = age
|
| 104 |
+
# A naive datetime
|
| 105 |
+
self.created = dt.datetime(2013, 11, 10, 14, 20, 58)
|
| 106 |
+
# A TZ-aware datetime
|
| 107 |
+
self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central)
|
| 108 |
+
self.id = id_
|
| 109 |
+
self.homepage = homepage
|
| 110 |
+
self.email = email
|
| 111 |
+
self.balance = balance
|
| 112 |
+
self.registered = registered
|
| 113 |
+
self.hair_colors = list(HairColorEnum.__members__)
|
| 114 |
+
self.sex_choices = list(GenderEnum.__members__)
|
| 115 |
+
self.finger_count = 10
|
| 116 |
+
self.uid = uuid.uuid1()
|
| 117 |
+
self.time_registered = time_registered or dt.time(1, 23, 45, 6789)
|
| 118 |
+
self.birthdate = birthdate or dt.date(2013, 1, 23)
|
| 119 |
+
self.birthtime = birthtime or dt.time(0, 1, 2, 3333)
|
| 120 |
+
self.activation_date = dt.date(2013, 12, 11)
|
| 121 |
+
self.sex = sex
|
| 122 |
+
self.hair_color = hair_color
|
| 123 |
+
self.employer = employer
|
| 124 |
+
self.relatives = []
|
| 125 |
+
self.various_data = various_data or {
|
| 126 |
+
"pets": ["cat", "dog"],
|
| 127 |
+
"address": "1600 Pennsylvania Ave\n" "Washington, DC 20006",
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def since_created(self):
|
| 132 |
+
return dt.datetime(2013, 11, 24) - self.created
|
| 133 |
+
|
| 134 |
+
def __repr__(self):
|
| 135 |
+
return f"<User {self.name}>"
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class Blog:
|
| 139 |
+
def __init__(self, title, user, collaborators=None, categories=None, id_=None):
|
| 140 |
+
self.title = title
|
| 141 |
+
self.user = user
|
| 142 |
+
self.collaborators = collaborators or [] # List/tuple of users
|
| 143 |
+
self.categories = categories
|
| 144 |
+
self.id = id_
|
| 145 |
+
|
| 146 |
+
def __contains__(self, item):
|
| 147 |
+
return item.name in [each.name for each in self.collaborators]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class DummyModel:
|
| 151 |
+
def __init__(self, foo):
|
| 152 |
+
self.foo = foo
|
| 153 |
+
|
| 154 |
+
def __eq__(self, other):
|
| 155 |
+
return self.foo == other.foo
|
| 156 |
+
|
| 157 |
+
def __str__(self):
|
| 158 |
+
return f"bar {self.foo}"
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
###### Schemas #####
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class Uppercased(fields.Field):
|
| 165 |
+
"""Custom field formatting example."""
|
| 166 |
+
|
| 167 |
+
def _serialize(self, value, attr, obj):
|
| 168 |
+
if value:
|
| 169 |
+
return value.upper()
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def get_lowername(obj):
|
| 173 |
+
if obj is None:
|
| 174 |
+
return missing
|
| 175 |
+
if isinstance(obj, dict):
|
| 176 |
+
return obj.get("name").lower()
|
| 177 |
+
else:
|
| 178 |
+
return obj.name.lower()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class UserSchema(Schema):
|
| 182 |
+
name = fields.String()
|
| 183 |
+
age = fields.Float() # type: fields.Field
|
| 184 |
+
created = fields.DateTime()
|
| 185 |
+
created_formatted = fields.DateTime(
|
| 186 |
+
format="%Y-%m-%d", attribute="created", dump_only=True
|
| 187 |
+
)
|
| 188 |
+
created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True)
|
| 189 |
+
updated = fields.DateTime()
|
| 190 |
+
species = fields.String(attribute="SPECIES")
|
| 191 |
+
id = fields.String(dump_default="no-id")
|
| 192 |
+
uppername = Uppercased(attribute="name", dump_only=True)
|
| 193 |
+
homepage = fields.Url()
|
| 194 |
+
email = fields.Email()
|
| 195 |
+
balance = fields.Decimal()
|
| 196 |
+
is_old = fields.Method("get_is_old") # type: fields.Field
|
| 197 |
+
lowername = fields.Function(get_lowername)
|
| 198 |
+
registered = fields.Boolean()
|
| 199 |
+
hair_colors = fields.List(fields.Raw)
|
| 200 |
+
sex_choices = fields.List(fields.Raw)
|
| 201 |
+
finger_count = fields.Integer()
|
| 202 |
+
uid = fields.UUID()
|
| 203 |
+
time_registered = fields.Time()
|
| 204 |
+
birthdate = fields.Date()
|
| 205 |
+
birthtime = fields.Time()
|
| 206 |
+
activation_date = fields.Date()
|
| 207 |
+
since_created = fields.TimeDelta()
|
| 208 |
+
sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__)))
|
| 209 |
+
various_data = fields.Dict()
|
| 210 |
+
|
| 211 |
+
class Meta:
|
| 212 |
+
render_module = simplejson
|
| 213 |
+
|
| 214 |
+
def get_is_old(self, obj):
|
| 215 |
+
if obj is None:
|
| 216 |
+
return missing
|
| 217 |
+
if isinstance(obj, dict):
|
| 218 |
+
age = obj.get("age")
|
| 219 |
+
else:
|
| 220 |
+
age = obj.age
|
| 221 |
+
try:
|
| 222 |
+
return age > 80
|
| 223 |
+
except TypeError as te:
|
| 224 |
+
raise ValidationError(str(te)) from te
|
| 225 |
+
|
| 226 |
+
@post_load
|
| 227 |
+
def make_user(self, data, **kwargs):
|
| 228 |
+
return User(**data)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class UserMetaSchema(Schema):
|
| 232 |
+
"""The equivalent of the UserSchema, using the ``fields`` option."""
|
| 233 |
+
|
| 234 |
+
uppername = Uppercased(attribute="name", dump_only=True)
|
| 235 |
+
balance = fields.Decimal()
|
| 236 |
+
is_old = fields.Method("get_is_old")
|
| 237 |
+
lowername = fields.Function(get_lowername)
|
| 238 |
+
species = fields.String(attribute="SPECIES")
|
| 239 |
+
homepage = fields.Url()
|
| 240 |
+
email = fields.Email()
|
| 241 |
+
various_data = fields.Dict()
|
| 242 |
+
|
| 243 |
+
def get_is_old(self, obj):
|
| 244 |
+
if obj is None:
|
| 245 |
+
return missing
|
| 246 |
+
if isinstance(obj, dict):
|
| 247 |
+
age = obj.get("age")
|
| 248 |
+
else:
|
| 249 |
+
age = obj.age
|
| 250 |
+
try:
|
| 251 |
+
return age > 80
|
| 252 |
+
except TypeError as te:
|
| 253 |
+
raise ValidationError(str(te)) from te
|
| 254 |
+
|
| 255 |
+
class Meta:
|
| 256 |
+
fields = (
|
| 257 |
+
"name",
|
| 258 |
+
"age",
|
| 259 |
+
"created",
|
| 260 |
+
"updated",
|
| 261 |
+
"id",
|
| 262 |
+
"homepage",
|
| 263 |
+
"uppername",
|
| 264 |
+
"email",
|
| 265 |
+
"balance",
|
| 266 |
+
"is_old",
|
| 267 |
+
"lowername",
|
| 268 |
+
"species",
|
| 269 |
+
"registered",
|
| 270 |
+
"hair_colors",
|
| 271 |
+
"sex_choices",
|
| 272 |
+
"finger_count",
|
| 273 |
+
"uid",
|
| 274 |
+
"time_registered",
|
| 275 |
+
"birthdate",
|
| 276 |
+
"birthtime",
|
| 277 |
+
"since_created",
|
| 278 |
+
"various_data",
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class UserExcludeSchema(UserSchema):
|
| 283 |
+
class Meta:
|
| 284 |
+
exclude = ("created", "updated")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class UserAdditionalSchema(Schema):
|
| 288 |
+
lowername = fields.Function(lambda obj: obj.name.lower())
|
| 289 |
+
|
| 290 |
+
class Meta:
|
| 291 |
+
additional = ("name", "age", "created", "email")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class UserIntSchema(UserSchema):
|
| 295 |
+
age = fields.Integer()
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class UserFloatStringSchema(UserSchema):
|
| 299 |
+
age = fields.Float(as_string=True)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class ExtendedUserSchema(UserSchema):
|
| 303 |
+
is_old = fields.Boolean()
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
class UserRelativeUrlSchema(UserSchema):
|
| 307 |
+
homepage = fields.Url(relative=True)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class BlogSchema(Schema):
|
| 311 |
+
title = fields.String()
|
| 312 |
+
user = fields.Nested(UserSchema)
|
| 313 |
+
collaborators = fields.List(fields.Nested(UserSchema()))
|
| 314 |
+
categories = fields.List(fields.String)
|
| 315 |
+
id = fields.String()
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class BlogUserMetaSchema(Schema):
|
| 319 |
+
user = fields.Nested(UserMetaSchema())
|
| 320 |
+
collaborators = fields.List(fields.Nested(UserMetaSchema()))
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class BlogSchemaMeta(Schema):
|
| 324 |
+
"""Same as BlogSerializer but using ``fields`` options."""
|
| 325 |
+
|
| 326 |
+
user = fields.Nested(UserSchema)
|
| 327 |
+
collaborators = fields.List(fields.Nested(UserSchema()))
|
| 328 |
+
|
| 329 |
+
class Meta:
|
| 330 |
+
fields = ("title", "user", "collaborators", "categories", "id")
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class BlogOnlySchema(Schema):
|
| 334 |
+
title = fields.String()
|
| 335 |
+
user = fields.Nested(UserSchema)
|
| 336 |
+
collaborators = fields.List(fields.Nested(UserSchema(only=("id",))))
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class BlogSchemaExclude(BlogSchema):
|
| 340 |
+
user = fields.Nested(UserSchema, exclude=("uppername", "species"))
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class BlogSchemaOnlyExclude(BlogSchema):
|
| 344 |
+
user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species"))
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
class mockjson: # noqa
|
| 348 |
+
@staticmethod
|
| 349 |
+
def dumps(val):
|
| 350 |
+
return b"{'foo': 42}"
|
| 351 |
+
|
| 352 |
+
@staticmethod
|
| 353 |
+
def loads(val):
|
| 354 |
+
return {"foo": 42}
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/conftest.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pytest fixtures that are available in all test modules."""
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from tests.base import Blog, User, UserSchema
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.fixture
|
| 9 |
+
def user():
|
| 10 |
+
return User(name="Monty", age=42.3, homepage="http://monty.python.org/")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.fixture
|
| 14 |
+
def blog(user):
|
| 15 |
+
col1 = User(name="Mick", age=123)
|
| 16 |
+
col2 = User(name="Keith", age=456)
|
| 17 |
+
return Blog(
|
| 18 |
+
"Monty's blog",
|
| 19 |
+
user=user,
|
| 20 |
+
categories=["humor", "violence"],
|
| 21 |
+
collaborators=[col1, col2],
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.fixture
|
| 26 |
+
def serialized_user(user):
|
| 27 |
+
return UserSchema().dump(user)
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/foo_serializer.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from marshmallow import Schema, fields
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class FooSerializer(Schema):
|
| 5 |
+
_id = fields.Integer()
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/mypy_test_cases/test_validation_error.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import marshmallow as ma
|
| 4 |
+
|
| 5 |
+
# OK types for 'message'
|
| 6 |
+
ma.ValidationError("foo")
|
| 7 |
+
ma.ValidationError(["foo"])
|
| 8 |
+
ma.ValidationError({"foo": "bar"})
|
| 9 |
+
|
| 10 |
+
# non-OK types for 'message'
|
| 11 |
+
ma.ValidationError(0) # type: ignore[arg-type]
|
| 12 |
+
|
| 13 |
+
# 'messages' is a dict|list
|
| 14 |
+
err = ma.ValidationError("foo")
|
| 15 |
+
a: dict | list = err.messages
|
| 16 |
+
# union type can't assign to non-union type
|
| 17 |
+
b: str = err.messages # type: ignore[assignment]
|
| 18 |
+
c: dict = err.messages # type: ignore[assignment]
|
| 19 |
+
# 'messages_dict' is a dict, so that it can assign to a dict
|
| 20 |
+
d: dict = err.messages_dict
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_decorators.py
ADDED
|
@@ -0,0 +1,896 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from marshmallow import (
|
| 4 |
+
EXCLUDE,
|
| 5 |
+
INCLUDE,
|
| 6 |
+
RAISE,
|
| 7 |
+
Schema,
|
| 8 |
+
ValidationError,
|
| 9 |
+
fields,
|
| 10 |
+
post_dump,
|
| 11 |
+
post_load,
|
| 12 |
+
pre_dump,
|
| 13 |
+
pre_load,
|
| 14 |
+
validates,
|
| 15 |
+
validates_schema,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest.mark.parametrize("partial_val", (True, False))
|
| 20 |
+
def test_decorated_processors(partial_val):
|
| 21 |
+
class ExampleSchema(Schema):
|
| 22 |
+
"""Includes different ways to invoke decorators and set up methods"""
|
| 23 |
+
|
| 24 |
+
TAG = "TAG"
|
| 25 |
+
|
| 26 |
+
value = fields.Integer(as_string=True)
|
| 27 |
+
|
| 28 |
+
# Implicit default raw, pre dump, static method.
|
| 29 |
+
@pre_dump
|
| 30 |
+
def increment_value(self, item, **kwargs):
|
| 31 |
+
assert "many" in kwargs
|
| 32 |
+
item["value"] += 1
|
| 33 |
+
return item
|
| 34 |
+
|
| 35 |
+
# Implicit default raw, post dump, class method.
|
| 36 |
+
@post_dump
|
| 37 |
+
def add_tag(self, item, **kwargs):
|
| 38 |
+
assert "many" in kwargs
|
| 39 |
+
item["value"] = self.TAG + item["value"]
|
| 40 |
+
return item
|
| 41 |
+
|
| 42 |
+
# Explicitly raw, post dump, instance method.
|
| 43 |
+
@post_dump(pass_many=True)
|
| 44 |
+
def add_envelope(self, data, many, **kwargs):
|
| 45 |
+
key = self.get_envelope_key(many)
|
| 46 |
+
return {key: data}
|
| 47 |
+
|
| 48 |
+
# Explicitly raw, pre load, instance method.
|
| 49 |
+
@pre_load(pass_many=True)
|
| 50 |
+
def remove_envelope(self, data, many, partial, **kwargs):
|
| 51 |
+
assert partial is partial_val
|
| 52 |
+
key = self.get_envelope_key(many)
|
| 53 |
+
return data[key]
|
| 54 |
+
|
| 55 |
+
@staticmethod
|
| 56 |
+
def get_envelope_key(many):
|
| 57 |
+
return "data" if many else "datum"
|
| 58 |
+
|
| 59 |
+
# Explicitly not raw, pre load, instance method.
|
| 60 |
+
@pre_load(pass_many=False)
|
| 61 |
+
def remove_tag(self, item, partial, **kwargs):
|
| 62 |
+
assert partial is partial_val
|
| 63 |
+
assert "many" in kwargs
|
| 64 |
+
item["value"] = item["value"][len(self.TAG) :]
|
| 65 |
+
return item
|
| 66 |
+
|
| 67 |
+
# Explicit default raw, post load, instance method.
|
| 68 |
+
@post_load()
|
| 69 |
+
def decrement_value(self, item, partial, **kwargs):
|
| 70 |
+
assert partial is partial_val
|
| 71 |
+
assert "many" in kwargs
|
| 72 |
+
item["value"] -= 1
|
| 73 |
+
return item
|
| 74 |
+
|
| 75 |
+
schema = ExampleSchema(partial=partial_val)
|
| 76 |
+
|
| 77 |
+
# Need to re-create these because the processors will modify in place.
|
| 78 |
+
make_item = lambda: {"value": 3}
|
| 79 |
+
make_items = lambda: [make_item(), {"value": 5}]
|
| 80 |
+
|
| 81 |
+
item_dumped = schema.dump(make_item())
|
| 82 |
+
assert item_dumped == {"datum": {"value": "TAG4"}}
|
| 83 |
+
item_loaded = schema.load(item_dumped)
|
| 84 |
+
assert item_loaded == make_item()
|
| 85 |
+
|
| 86 |
+
items_dumped = schema.dump(make_items(), many=True)
|
| 87 |
+
assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]}
|
| 88 |
+
items_loaded = schema.load(items_dumped, many=True)
|
| 89 |
+
assert items_loaded == make_items()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/347
|
| 93 |
+
@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE))
|
| 94 |
+
def test_decorated_processor_returning_none(unknown):
|
| 95 |
+
class PostSchema(Schema):
|
| 96 |
+
value = fields.Integer()
|
| 97 |
+
|
| 98 |
+
@post_load
|
| 99 |
+
def load_none(self, item, **kwargs):
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
@post_dump
|
| 103 |
+
def dump_none(self, item, **kwargs):
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
class PreSchema(Schema):
|
| 107 |
+
value = fields.Integer()
|
| 108 |
+
|
| 109 |
+
@pre_load
|
| 110 |
+
def load_none(self, item, **kwargs):
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
@pre_dump
|
| 114 |
+
def dump_none(self, item, **kwargs):
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
schema = PostSchema(unknown=unknown)
|
| 118 |
+
assert schema.dump({"value": 3}) is None
|
| 119 |
+
assert schema.load({"value": 3}) is None
|
| 120 |
+
schema = PreSchema(unknown=unknown)
|
| 121 |
+
assert schema.dump({"value": 3}) == {}
|
| 122 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 123 |
+
schema.load({"value": 3})
|
| 124 |
+
assert excinfo.value.messages == {"_schema": ["Invalid input type."]}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class TestPassOriginal:
|
| 128 |
+
def test_pass_original_single(self):
|
| 129 |
+
class MySchema(Schema):
|
| 130 |
+
foo = fields.Field()
|
| 131 |
+
|
| 132 |
+
@post_load(pass_original=True)
|
| 133 |
+
def post_load(self, data, original_data, **kwargs):
|
| 134 |
+
ret = data.copy()
|
| 135 |
+
ret["_post_load"] = original_data["sentinel"]
|
| 136 |
+
return ret
|
| 137 |
+
|
| 138 |
+
@post_dump(pass_original=True)
|
| 139 |
+
def post_dump(self, data, obj, **kwargs):
|
| 140 |
+
ret = data.copy()
|
| 141 |
+
ret["_post_dump"] = obj["sentinel"]
|
| 142 |
+
return ret
|
| 143 |
+
|
| 144 |
+
schema = MySchema(unknown=EXCLUDE)
|
| 145 |
+
datum = {"foo": 42, "sentinel": 24}
|
| 146 |
+
item_loaded = schema.load(datum)
|
| 147 |
+
assert item_loaded["foo"] == 42
|
| 148 |
+
assert item_loaded["_post_load"] == 24
|
| 149 |
+
|
| 150 |
+
item_dumped = schema.dump(datum)
|
| 151 |
+
|
| 152 |
+
assert item_dumped["foo"] == 42
|
| 153 |
+
assert item_dumped["_post_dump"] == 24
|
| 154 |
+
|
| 155 |
+
def test_pass_original_many(self):
|
| 156 |
+
class MySchema(Schema):
|
| 157 |
+
foo = fields.Field()
|
| 158 |
+
|
| 159 |
+
@post_load(pass_many=True, pass_original=True)
|
| 160 |
+
def post_load(self, data, original, many, **kwargs):
|
| 161 |
+
if many:
|
| 162 |
+
ret = []
|
| 163 |
+
for item, orig_item in zip(data, original):
|
| 164 |
+
item["_post_load"] = orig_item["sentinel"]
|
| 165 |
+
ret.append(item)
|
| 166 |
+
else:
|
| 167 |
+
ret = data.copy()
|
| 168 |
+
ret["_post_load"] = original["sentinel"]
|
| 169 |
+
return ret
|
| 170 |
+
|
| 171 |
+
@post_dump(pass_many=True, pass_original=True)
|
| 172 |
+
def post_dump(self, data, original, many, **kwargs):
|
| 173 |
+
if many:
|
| 174 |
+
ret = []
|
| 175 |
+
for item, orig_item in zip(data, original):
|
| 176 |
+
item["_post_dump"] = orig_item["sentinel"]
|
| 177 |
+
ret.append(item)
|
| 178 |
+
else:
|
| 179 |
+
ret = data.copy()
|
| 180 |
+
ret["_post_dump"] = original["sentinel"]
|
| 181 |
+
return ret
|
| 182 |
+
|
| 183 |
+
schema = MySchema(unknown=EXCLUDE)
|
| 184 |
+
data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}]
|
| 185 |
+
items_loaded = schema.load(data, many=True)
|
| 186 |
+
assert items_loaded == [
|
| 187 |
+
{"foo": 42, "_post_load": 24},
|
| 188 |
+
{"foo": 424, "_post_load": 242},
|
| 189 |
+
]
|
| 190 |
+
test_values = [e["_post_load"] for e in items_loaded]
|
| 191 |
+
assert test_values == [24, 242]
|
| 192 |
+
|
| 193 |
+
items_dumped = schema.dump(data, many=True)
|
| 194 |
+
assert items_dumped == [
|
| 195 |
+
{"foo": 42, "_post_dump": 24},
|
| 196 |
+
{"foo": 424, "_post_dump": 242},
|
| 197 |
+
]
|
| 198 |
+
|
| 199 |
+
# Also check load/dump of single item
|
| 200 |
+
|
| 201 |
+
datum = {"foo": 42, "sentinel": 24}
|
| 202 |
+
item_loaded = schema.load(datum, many=False)
|
| 203 |
+
assert item_loaded == {"foo": 42, "_post_load": 24}
|
| 204 |
+
|
| 205 |
+
item_dumped = schema.dump(datum, many=False)
|
| 206 |
+
assert item_dumped == {"foo": 42, "_post_dump": 24}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def test_decorated_processor_inheritance():
|
| 210 |
+
class ParentSchema(Schema):
|
| 211 |
+
@post_dump
|
| 212 |
+
def inherited(self, item, **kwargs):
|
| 213 |
+
item["inherited"] = "inherited"
|
| 214 |
+
return item
|
| 215 |
+
|
| 216 |
+
@post_dump
|
| 217 |
+
def overridden(self, item, **kwargs):
|
| 218 |
+
item["overridden"] = "base"
|
| 219 |
+
return item
|
| 220 |
+
|
| 221 |
+
@post_dump
|
| 222 |
+
def deleted(self, item, **kwargs):
|
| 223 |
+
item["deleted"] = "retained"
|
| 224 |
+
return item
|
| 225 |
+
|
| 226 |
+
class ChildSchema(ParentSchema):
|
| 227 |
+
@post_dump
|
| 228 |
+
def overridden(self, item, **kwargs):
|
| 229 |
+
item["overridden"] = "overridden"
|
| 230 |
+
return item
|
| 231 |
+
|
| 232 |
+
deleted = None
|
| 233 |
+
|
| 234 |
+
parent_dumped = ParentSchema().dump({})
|
| 235 |
+
assert parent_dumped == {
|
| 236 |
+
"inherited": "inherited",
|
| 237 |
+
"overridden": "base",
|
| 238 |
+
"deleted": "retained",
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
child_dumped = ChildSchema().dump({})
|
| 242 |
+
assert child_dumped == {"inherited": "inherited", "overridden": "overridden"}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436
|
| 246 |
+
def test_pre_dump_is_invoked_before_implicit_field_generation():
|
| 247 |
+
class Foo(Schema):
|
| 248 |
+
field = fields.Integer()
|
| 249 |
+
|
| 250 |
+
@pre_dump
|
| 251 |
+
def hook(self, data, **kwargs):
|
| 252 |
+
data["generated_field"] = 7
|
| 253 |
+
return data
|
| 254 |
+
|
| 255 |
+
class Meta:
|
| 256 |
+
# Removing generated_field from here drops it from the output
|
| 257 |
+
fields = ("field", "generated_field")
|
| 258 |
+
|
| 259 |
+
assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7}
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class ValidatesSchema(Schema):
|
| 263 |
+
foo = fields.Int()
|
| 264 |
+
|
| 265 |
+
@validates("foo")
|
| 266 |
+
def validate_foo(self, value):
|
| 267 |
+
if value != 42:
|
| 268 |
+
raise ValidationError("The answer to life the universe and everything.")
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class TestValidatesDecorator:
|
| 272 |
+
def test_validates(self):
|
| 273 |
+
class VSchema(Schema):
|
| 274 |
+
s = fields.String()
|
| 275 |
+
|
| 276 |
+
@validates("s")
|
| 277 |
+
def validate_string(self, data):
|
| 278 |
+
raise ValidationError("nope")
|
| 279 |
+
|
| 280 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 281 |
+
VSchema().load({"s": "bar"})
|
| 282 |
+
|
| 283 |
+
assert excinfo.value.messages == {"s": ["nope"]}
|
| 284 |
+
|
| 285 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/350
|
| 286 |
+
def test_validates_with_attribute(self):
|
| 287 |
+
class S1(Schema):
|
| 288 |
+
s = fields.String(attribute="string_name")
|
| 289 |
+
|
| 290 |
+
@validates("s")
|
| 291 |
+
def validate_string(self, data):
|
| 292 |
+
raise ValidationError("nope")
|
| 293 |
+
|
| 294 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 295 |
+
S1().load({"s": "foo"})
|
| 296 |
+
assert excinfo.value.messages == {"s": ["nope"]}
|
| 297 |
+
|
| 298 |
+
with pytest.raises(ValidationError):
|
| 299 |
+
S1(many=True).load([{"s": "foo"}])
|
| 300 |
+
|
| 301 |
+
def test_validates_decorator(self):
|
| 302 |
+
schema = ValidatesSchema()
|
| 303 |
+
|
| 304 |
+
errors = schema.validate({"foo": 41})
|
| 305 |
+
assert "foo" in errors
|
| 306 |
+
assert errors["foo"][0] == "The answer to life the universe and everything."
|
| 307 |
+
|
| 308 |
+
errors = schema.validate({"foo": 42})
|
| 309 |
+
assert errors == {}
|
| 310 |
+
|
| 311 |
+
errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True)
|
| 312 |
+
assert "foo" in errors[1]
|
| 313 |
+
assert len(errors[1]["foo"]) == 1
|
| 314 |
+
assert errors[1]["foo"][0] == "The answer to life the universe and everything."
|
| 315 |
+
|
| 316 |
+
errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True)
|
| 317 |
+
assert errors == {}
|
| 318 |
+
|
| 319 |
+
errors = schema.validate({})
|
| 320 |
+
assert errors == {}
|
| 321 |
+
|
| 322 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 323 |
+
schema.load({"foo": 41})
|
| 324 |
+
errors = excinfo.value.messages
|
| 325 |
+
result = excinfo.value.valid_data
|
| 326 |
+
assert errors
|
| 327 |
+
assert result == {}
|
| 328 |
+
|
| 329 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 330 |
+
schema.load([{"foo": 42}, {"foo": 43}], many=True)
|
| 331 |
+
errors = excinfo.value.messages
|
| 332 |
+
result = excinfo.value.valid_data
|
| 333 |
+
assert len(result) == 2
|
| 334 |
+
assert result[0] == {"foo": 42}
|
| 335 |
+
assert result[1] == {}
|
| 336 |
+
assert 1 in errors
|
| 337 |
+
assert "foo" in errors[1]
|
| 338 |
+
assert errors[1]["foo"] == ["The answer to life the universe and everything."]
|
| 339 |
+
|
| 340 |
+
def test_field_not_present(self):
|
| 341 |
+
class BadSchema(ValidatesSchema):
|
| 342 |
+
@validates("bar")
|
| 343 |
+
def validate_bar(self, value):
|
| 344 |
+
raise ValidationError("Never raised.")
|
| 345 |
+
|
| 346 |
+
schema = BadSchema()
|
| 347 |
+
|
| 348 |
+
with pytest.raises(ValueError, match='"bar" field does not exist.'):
|
| 349 |
+
schema.validate({"foo": 42})
|
| 350 |
+
|
| 351 |
+
def test_precedence(self):
|
| 352 |
+
class Schema2(ValidatesSchema):
|
| 353 |
+
foo = fields.Int(validate=lambda n: n != 42)
|
| 354 |
+
bar = fields.Int(validate=lambda n: n == 1)
|
| 355 |
+
|
| 356 |
+
@validates("bar")
|
| 357 |
+
def validate_bar(self, value):
|
| 358 |
+
if value != 2:
|
| 359 |
+
raise ValidationError("Must be 2")
|
| 360 |
+
|
| 361 |
+
schema = Schema2()
|
| 362 |
+
|
| 363 |
+
errors = schema.validate({"foo": 42})
|
| 364 |
+
assert "foo" in errors
|
| 365 |
+
assert len(errors["foo"]) == 1
|
| 366 |
+
assert "Invalid value." in errors["foo"][0]
|
| 367 |
+
|
| 368 |
+
errors = schema.validate({"bar": 3})
|
| 369 |
+
assert "bar" in errors
|
| 370 |
+
assert len(errors["bar"]) == 1
|
| 371 |
+
assert "Invalid value." in errors["bar"][0]
|
| 372 |
+
|
| 373 |
+
errors = schema.validate({"bar": 1})
|
| 374 |
+
assert "bar" in errors
|
| 375 |
+
assert len(errors["bar"]) == 1
|
| 376 |
+
assert errors["bar"][0] == "Must be 2"
|
| 377 |
+
|
| 378 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/748
|
| 379 |
+
def test_validates_with_data_key(self):
|
| 380 |
+
class BadSchema(Schema):
|
| 381 |
+
foo = fields.String(data_key="foo-name")
|
| 382 |
+
|
| 383 |
+
@validates("foo")
|
| 384 |
+
def validate_string(self, data):
|
| 385 |
+
raise ValidationError("nope")
|
| 386 |
+
|
| 387 |
+
schema = BadSchema()
|
| 388 |
+
errors = schema.validate({"foo-name": "data"})
|
| 389 |
+
assert "foo-name" in errors
|
| 390 |
+
assert errors["foo-name"] == ["nope"]
|
| 391 |
+
|
| 392 |
+
schema = BadSchema()
|
| 393 |
+
errors = schema.validate(
|
| 394 |
+
[{"foo-name": "data"}, {"foo-name": "data2"}], many=True
|
| 395 |
+
)
|
| 396 |
+
assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}}
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
class TestValidatesSchemaDecorator:
|
| 400 |
+
def test_validator_nested_many_invalid_data(self):
|
| 401 |
+
class NestedSchema(Schema):
|
| 402 |
+
foo = fields.Int(required=True)
|
| 403 |
+
|
| 404 |
+
class MySchema(Schema):
|
| 405 |
+
nested = fields.Nested(NestedSchema, required=True, many=True)
|
| 406 |
+
|
| 407 |
+
schema = MySchema()
|
| 408 |
+
errors = schema.validate({"nested": [1]})
|
| 409 |
+
assert errors
|
| 410 |
+
assert "nested" in errors
|
| 411 |
+
assert 0 in errors["nested"]
|
| 412 |
+
assert errors["nested"][0] == {"_schema": ["Invalid input type."]}
|
| 413 |
+
|
| 414 |
+
def test_validator_nested_many_schema_error(self):
|
| 415 |
+
class NestedSchema(Schema):
|
| 416 |
+
foo = fields.Int(required=True)
|
| 417 |
+
|
| 418 |
+
@validates_schema
|
| 419 |
+
def validate_schema(self, data, **kwargs):
|
| 420 |
+
raise ValidationError("This will never work.")
|
| 421 |
+
|
| 422 |
+
class MySchema(Schema):
|
| 423 |
+
nested = fields.Nested(NestedSchema, required=True, many=True)
|
| 424 |
+
|
| 425 |
+
schema = MySchema()
|
| 426 |
+
errors = schema.validate({"nested": [{"foo": 1}]})
|
| 427 |
+
assert errors
|
| 428 |
+
assert "nested" in errors
|
| 429 |
+
assert 0 in errors["nested"]
|
| 430 |
+
assert errors["nested"][0] == {"_schema": ["This will never work."]}
|
| 431 |
+
|
| 432 |
+
def test_validator_nested_many_field_error(self):
|
| 433 |
+
class NestedSchema(Schema):
|
| 434 |
+
foo = fields.Int(required=True)
|
| 435 |
+
|
| 436 |
+
@validates_schema
|
| 437 |
+
def validate_schema(self, data, **kwargs):
|
| 438 |
+
raise ValidationError("This will never work.", "foo")
|
| 439 |
+
|
| 440 |
+
class MySchema(Schema):
|
| 441 |
+
nested = fields.Nested(NestedSchema, required=True, many=True)
|
| 442 |
+
|
| 443 |
+
schema = MySchema()
|
| 444 |
+
errors = schema.validate({"nested": [{"foo": 1}]})
|
| 445 |
+
assert errors
|
| 446 |
+
assert "nested" in errors
|
| 447 |
+
assert 0 in errors["nested"]
|
| 448 |
+
assert errors["nested"][0] == {"foo": ["This will never work."]}
|
| 449 |
+
|
| 450 |
+
@pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],))
|
| 451 |
+
@pytest.mark.parametrize(
|
| 452 |
+
"pass_many,expected_data,expected_original_data",
|
| 453 |
+
(
|
| 454 |
+
[True, [{"foo": 1}], [{"foo": 1, "bar": 2}]],
|
| 455 |
+
[False, {"foo": 1}, {"foo": 1, "bar": 2}],
|
| 456 |
+
),
|
| 457 |
+
)
|
| 458 |
+
def test_validator_nested_many_pass_original_and_pass_many(
|
| 459 |
+
self, pass_many, data, expected_data, expected_original_data
|
| 460 |
+
):
|
| 461 |
+
class NestedSchema(Schema):
|
| 462 |
+
foo = fields.Int(required=True)
|
| 463 |
+
|
| 464 |
+
@validates_schema(pass_many=pass_many, pass_original=True)
|
| 465 |
+
def validate_schema(self, data, original_data, many, **kwargs):
|
| 466 |
+
assert data == expected_data
|
| 467 |
+
assert original_data == expected_original_data
|
| 468 |
+
assert many is True
|
| 469 |
+
raise ValidationError("Method called")
|
| 470 |
+
|
| 471 |
+
class MySchema(Schema):
|
| 472 |
+
nested = fields.Nested(
|
| 473 |
+
NestedSchema, required=True, many=True, unknown=EXCLUDE
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
schema = MySchema()
|
| 477 |
+
errors = schema.validate({"nested": data})
|
| 478 |
+
error = errors["nested"] if pass_many else errors["nested"][0]
|
| 479 |
+
assert error["_schema"][0] == "Method called"
|
| 480 |
+
|
| 481 |
+
def test_decorated_validators(self):
|
| 482 |
+
class MySchema(Schema):
|
| 483 |
+
foo = fields.Int()
|
| 484 |
+
bar = fields.Int()
|
| 485 |
+
|
| 486 |
+
@validates_schema
|
| 487 |
+
def validate_schema(self, data, **kwargs):
|
| 488 |
+
if data["foo"] <= 3:
|
| 489 |
+
raise ValidationError("Must be greater than 3")
|
| 490 |
+
|
| 491 |
+
@validates_schema(pass_many=True)
|
| 492 |
+
def validate_raw(self, data, many, **kwargs):
|
| 493 |
+
if many:
|
| 494 |
+
assert type(data) is list
|
| 495 |
+
if len(data) < 2:
|
| 496 |
+
raise ValidationError("Must provide at least 2 items")
|
| 497 |
+
|
| 498 |
+
@validates_schema
|
| 499 |
+
def validate_bar(self, data, **kwargs):
|
| 500 |
+
if "bar" in data and data["bar"] < 0:
|
| 501 |
+
raise ValidationError("bar must not be negative", "bar")
|
| 502 |
+
|
| 503 |
+
schema = MySchema()
|
| 504 |
+
errors = schema.validate({"foo": 3})
|
| 505 |
+
assert "_schema" in errors
|
| 506 |
+
assert errors["_schema"][0] == "Must be greater than 3"
|
| 507 |
+
|
| 508 |
+
errors = schema.validate([{"foo": 4}], many=True)
|
| 509 |
+
assert "_schema" in errors
|
| 510 |
+
assert len(errors["_schema"]) == 1
|
| 511 |
+
assert errors["_schema"][0] == "Must provide at least 2 items"
|
| 512 |
+
|
| 513 |
+
errors = schema.validate({"foo": 4, "bar": -1})
|
| 514 |
+
assert "bar" in errors
|
| 515 |
+
assert len(errors["bar"]) == 1
|
| 516 |
+
assert errors["bar"][0] == "bar must not be negative"
|
| 517 |
+
|
| 518 |
+
def test_multiple_validators(self):
|
| 519 |
+
class MySchema(Schema):
|
| 520 |
+
foo = fields.Int()
|
| 521 |
+
bar = fields.Int()
|
| 522 |
+
|
| 523 |
+
@validates_schema
|
| 524 |
+
def validate_schema(self, data, **kwargs):
|
| 525 |
+
if data["foo"] <= 3:
|
| 526 |
+
raise ValidationError("Must be greater than 3")
|
| 527 |
+
|
| 528 |
+
@validates_schema
|
| 529 |
+
def validate_bar(self, data, **kwargs):
|
| 530 |
+
if "bar" in data and data["bar"] < 0:
|
| 531 |
+
raise ValidationError("bar must not be negative")
|
| 532 |
+
|
| 533 |
+
schema = MySchema()
|
| 534 |
+
errors = schema.validate({"foo": 3, "bar": -1})
|
| 535 |
+
assert type(errors) is dict
|
| 536 |
+
assert "_schema" in errors
|
| 537 |
+
assert len(errors["_schema"]) == 2
|
| 538 |
+
assert "Must be greater than 3" in errors["_schema"]
|
| 539 |
+
assert "bar must not be negative" in errors["_schema"]
|
| 540 |
+
|
| 541 |
+
errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True)
|
| 542 |
+
assert type(errors) is dict
|
| 543 |
+
assert "_schema" in errors[0]
|
| 544 |
+
assert len(errors[0]["_schema"]) == 2
|
| 545 |
+
assert "Must be greater than 3" in errors[0]["_schema"]
|
| 546 |
+
assert "bar must not be negative" in errors[0]["_schema"]
|
| 547 |
+
assert len(errors[1]["_schema"]) == 1
|
| 548 |
+
assert "Must be greater than 3" in errors[0]["_schema"]
|
| 549 |
+
|
| 550 |
+
def test_multiple_validators_merge_dict_errors(self):
|
| 551 |
+
class NestedSchema(Schema):
|
| 552 |
+
foo = fields.Int()
|
| 553 |
+
bar = fields.Int()
|
| 554 |
+
|
| 555 |
+
class MySchema(Schema):
|
| 556 |
+
nested = fields.Nested(NestedSchema)
|
| 557 |
+
|
| 558 |
+
@validates_schema
|
| 559 |
+
def validate_nested_foo(self, data, **kwargs):
|
| 560 |
+
raise ValidationError({"nested": {"foo": ["Invalid foo"]}})
|
| 561 |
+
|
| 562 |
+
@validates_schema
|
| 563 |
+
def validate_nested_bar_1(self, data, **kwargs):
|
| 564 |
+
raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}})
|
| 565 |
+
|
| 566 |
+
@validates_schema
|
| 567 |
+
def validate_nested_bar_2(self, data, **kwargs):
|
| 568 |
+
raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}})
|
| 569 |
+
|
| 570 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 571 |
+
MySchema().load({"nested": {"foo": 1, "bar": 2}})
|
| 572 |
+
|
| 573 |
+
assert excinfo.value.messages == {
|
| 574 |
+
"nested": {
|
| 575 |
+
"foo": ["Invalid foo"],
|
| 576 |
+
"bar": ["Invalid bar 1", "Invalid bar 2"],
|
| 577 |
+
}
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
def test_passing_original_data(self):
|
| 581 |
+
class MySchema(Schema):
|
| 582 |
+
foo = fields.Int()
|
| 583 |
+
bar = fields.Int()
|
| 584 |
+
|
| 585 |
+
@validates_schema(pass_original=True)
|
| 586 |
+
def validate_original(self, data, original_data, partial, **kwargs):
|
| 587 |
+
if isinstance(original_data, dict) and isinstance(
|
| 588 |
+
original_data["foo"], str
|
| 589 |
+
):
|
| 590 |
+
raise ValidationError("foo cannot be a string")
|
| 591 |
+
|
| 592 |
+
@validates_schema(pass_many=True, pass_original=True)
|
| 593 |
+
def validate_original_bar(self, data, original_data, many, **kwargs):
|
| 594 |
+
def check(datum):
|
| 595 |
+
if isinstance(datum, dict) and isinstance(datum["bar"], str):
|
| 596 |
+
raise ValidationError("bar cannot be a string")
|
| 597 |
+
|
| 598 |
+
if many:
|
| 599 |
+
for each in original_data:
|
| 600 |
+
check(each)
|
| 601 |
+
else:
|
| 602 |
+
check(original_data)
|
| 603 |
+
|
| 604 |
+
schema = MySchema()
|
| 605 |
+
|
| 606 |
+
errors = schema.validate({"foo": "4", "bar": 12})
|
| 607 |
+
assert errors["_schema"] == ["foo cannot be a string"]
|
| 608 |
+
|
| 609 |
+
errors = schema.validate({"foo": 4, "bar": "42"})
|
| 610 |
+
assert errors["_schema"] == ["bar cannot be a string"]
|
| 611 |
+
|
| 612 |
+
errors = schema.validate([{"foo": 4, "bar": "42"}], many=True)
|
| 613 |
+
assert errors["_schema"] == ["bar cannot be a string"]
|
| 614 |
+
|
| 615 |
+
def test_allow_reporting_field_errors_in_schema_validator(self):
|
| 616 |
+
class NestedSchema(Schema):
|
| 617 |
+
baz = fields.Int(required=True)
|
| 618 |
+
|
| 619 |
+
class MySchema(Schema):
|
| 620 |
+
foo = fields.Int(required=True)
|
| 621 |
+
bar = fields.Nested(NestedSchema, required=True)
|
| 622 |
+
bam = fields.Int(required=True)
|
| 623 |
+
|
| 624 |
+
@validates_schema(skip_on_field_errors=True)
|
| 625 |
+
def consistency_validation(self, data, **kwargs):
|
| 626 |
+
errors = {}
|
| 627 |
+
if data["bar"]["baz"] != data["foo"]:
|
| 628 |
+
errors["bar"] = {"baz": "Non-matching value"}
|
| 629 |
+
if data["bam"] > data["foo"]:
|
| 630 |
+
errors["bam"] = "Value should be less than foo"
|
| 631 |
+
if errors:
|
| 632 |
+
raise ValidationError(errors)
|
| 633 |
+
|
| 634 |
+
schema = MySchema()
|
| 635 |
+
errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6})
|
| 636 |
+
assert errors["bar"]["baz"] == "Non-matching value"
|
| 637 |
+
assert errors["bam"] == "Value should be less than foo"
|
| 638 |
+
|
| 639 |
+
# https://github.com/marshmallow-code/marshmallow/issues/273
|
| 640 |
+
def test_allow_arbitrary_field_names_in_error(self):
|
| 641 |
+
class MySchema(Schema):
|
| 642 |
+
@validates_schema
|
| 643 |
+
def validator(self, data, **kwargs):
|
| 644 |
+
raise ValidationError("Error message", "arbitrary_key")
|
| 645 |
+
|
| 646 |
+
errors = MySchema().validate({})
|
| 647 |
+
assert errors["arbitrary_key"] == ["Error message"]
|
| 648 |
+
|
| 649 |
+
def test_skip_on_field_errors(self):
|
| 650 |
+
class MySchema(Schema):
|
| 651 |
+
foo = fields.Int(required=True, validate=lambda n: n == 3)
|
| 652 |
+
bar = fields.Int(required=True)
|
| 653 |
+
|
| 654 |
+
@validates_schema(skip_on_field_errors=True)
|
| 655 |
+
def validate_schema(self, data, **kwargs):
|
| 656 |
+
if data["foo"] != data["bar"]:
|
| 657 |
+
raise ValidationError("Foo and bar must be equal.")
|
| 658 |
+
|
| 659 |
+
@validates_schema(skip_on_field_errors=True, pass_many=True)
|
| 660 |
+
def validate_many(self, data, many, **kwargs):
|
| 661 |
+
if many:
|
| 662 |
+
assert type(data) is list
|
| 663 |
+
if len(data) < 2:
|
| 664 |
+
raise ValidationError("Must provide at least 2 items")
|
| 665 |
+
|
| 666 |
+
schema = MySchema()
|
| 667 |
+
# check that schema errors still occur with no field errors
|
| 668 |
+
errors = schema.validate({"foo": 3, "bar": 4})
|
| 669 |
+
assert "_schema" in errors
|
| 670 |
+
assert errors["_schema"][0] == "Foo and bar must be equal."
|
| 671 |
+
|
| 672 |
+
errors = schema.validate([{"foo": 3, "bar": 3}], many=True)
|
| 673 |
+
assert "_schema" in errors
|
| 674 |
+
assert errors["_schema"][0] == "Must provide at least 2 items"
|
| 675 |
+
|
| 676 |
+
# check that schema errors don't occur when field errors do
|
| 677 |
+
errors = schema.validate({"foo": 3, "bar": "not an int"})
|
| 678 |
+
assert "bar" in errors
|
| 679 |
+
assert "_schema" not in errors
|
| 680 |
+
|
| 681 |
+
errors = schema.validate({"foo": 2, "bar": 2})
|
| 682 |
+
assert "foo" in errors
|
| 683 |
+
assert "_schema" not in errors
|
| 684 |
+
|
| 685 |
+
errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True)
|
| 686 |
+
assert "bar" in errors[0]
|
| 687 |
+
assert "_schema" not in errors
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def test_decorator_error_handling(): # noqa: C901
|
| 691 |
+
class ExampleSchema(Schema):
|
| 692 |
+
foo = fields.Int()
|
| 693 |
+
bar = fields.Int()
|
| 694 |
+
|
| 695 |
+
@pre_load()
|
| 696 |
+
def pre_load_error1(self, item, **kwargs):
|
| 697 |
+
if item["foo"] != 0:
|
| 698 |
+
return item
|
| 699 |
+
errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]}
|
| 700 |
+
raise ValidationError(errors)
|
| 701 |
+
|
| 702 |
+
@pre_load()
|
| 703 |
+
def pre_load_error2(self, item, **kwargs):
|
| 704 |
+
if item["foo"] != 4:
|
| 705 |
+
return item
|
| 706 |
+
raise ValidationError("preloadmsg1", "foo")
|
| 707 |
+
|
| 708 |
+
@pre_load()
|
| 709 |
+
def pre_load_error3(self, item, **kwargs):
|
| 710 |
+
if item["foo"] != 8:
|
| 711 |
+
return item
|
| 712 |
+
raise ValidationError("preloadmsg1")
|
| 713 |
+
|
| 714 |
+
@post_load()
|
| 715 |
+
def post_load_error1(self, item, **kwargs):
|
| 716 |
+
if item["foo"] != 1:
|
| 717 |
+
return item
|
| 718 |
+
errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]}
|
| 719 |
+
raise ValidationError(errors)
|
| 720 |
+
|
| 721 |
+
@post_load()
|
| 722 |
+
def post_load_error2(self, item, **kwargs):
|
| 723 |
+
if item["foo"] != 5:
|
| 724 |
+
return item
|
| 725 |
+
raise ValidationError("postloadmsg1", "foo")
|
| 726 |
+
|
| 727 |
+
def make_item(foo, bar):
|
| 728 |
+
data = schema.load({"foo": foo, "bar": bar})
|
| 729 |
+
assert data is not None
|
| 730 |
+
return data
|
| 731 |
+
|
| 732 |
+
schema = ExampleSchema()
|
| 733 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 734 |
+
schema.load({"foo": 0, "bar": 1})
|
| 735 |
+
errors = excinfo.value.messages
|
| 736 |
+
assert "foo" in errors
|
| 737 |
+
assert len(errors["foo"]) == 1
|
| 738 |
+
assert errors["foo"][0] == "preloadmsg1"
|
| 739 |
+
assert "bar" in errors
|
| 740 |
+
assert len(errors["bar"]) == 2
|
| 741 |
+
assert "preloadmsg2" in errors["bar"]
|
| 742 |
+
assert "preloadmsg3" in errors["bar"]
|
| 743 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 744 |
+
schema.load({"foo": 1, "bar": 1})
|
| 745 |
+
errors = excinfo.value.messages
|
| 746 |
+
assert "foo" in errors
|
| 747 |
+
assert len(errors["foo"]) == 1
|
| 748 |
+
assert errors["foo"][0] == "postloadmsg1"
|
| 749 |
+
assert "bar" in errors
|
| 750 |
+
assert len(errors["bar"]) == 2
|
| 751 |
+
assert "postloadmsg2" in errors["bar"]
|
| 752 |
+
assert "postloadmsg3" in errors["bar"]
|
| 753 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 754 |
+
schema.load({"foo": 4, "bar": 1})
|
| 755 |
+
errors = excinfo.value.messages
|
| 756 |
+
assert len(errors) == 1
|
| 757 |
+
assert "foo" in errors
|
| 758 |
+
assert len(errors["foo"]) == 1
|
| 759 |
+
assert errors["foo"][0] == "preloadmsg1"
|
| 760 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 761 |
+
schema.load({"foo": 5, "bar": 1})
|
| 762 |
+
errors = excinfo.value.messages
|
| 763 |
+
assert len(errors) == 1
|
| 764 |
+
assert "foo" in errors
|
| 765 |
+
assert len(errors["foo"]) == 1
|
| 766 |
+
assert errors["foo"][0] == "postloadmsg1"
|
| 767 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 768 |
+
schema.load({"foo": 8, "bar": 1})
|
| 769 |
+
errors = excinfo.value.messages
|
| 770 |
+
assert len(errors) == 1
|
| 771 |
+
assert "_schema" in errors
|
| 772 |
+
assert len(errors["_schema"]) == 1
|
| 773 |
+
assert errors["_schema"][0] == "preloadmsg1"
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
@pytest.mark.parametrize("decorator", [pre_load, post_load])
|
| 777 |
+
def test_decorator_error_handling_with_load(decorator):
|
| 778 |
+
class ExampleSchema(Schema):
|
| 779 |
+
@decorator
|
| 780 |
+
def raise_value_error(self, item, **kwargs):
|
| 781 |
+
raise ValidationError({"foo": "error"})
|
| 782 |
+
|
| 783 |
+
schema = ExampleSchema()
|
| 784 |
+
with pytest.raises(ValidationError) as exc:
|
| 785 |
+
schema.load({})
|
| 786 |
+
assert exc.value.messages == {"foo": "error"}
|
| 787 |
+
schema.dump(object())
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
@pytest.mark.parametrize("decorator", [pre_load, post_load])
|
| 791 |
+
def test_decorator_error_handling_with_load_dict_error(decorator):
|
| 792 |
+
class ExampleSchema(Schema):
|
| 793 |
+
@decorator
|
| 794 |
+
def raise_value_error(self, item, **kwargs):
|
| 795 |
+
raise ValidationError({"foo": "error"}, "nested_field")
|
| 796 |
+
|
| 797 |
+
schema = ExampleSchema()
|
| 798 |
+
with pytest.raises(ValidationError) as exc:
|
| 799 |
+
schema.load({})
|
| 800 |
+
assert exc.value.messages == {"nested_field": {"foo": "error"}}
|
| 801 |
+
schema.dump(object())
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
@pytest.mark.parametrize("decorator", [pre_dump, post_dump])
|
| 805 |
+
def test_decorator_error_handling_with_dump(decorator):
|
| 806 |
+
class ExampleSchema(Schema):
|
| 807 |
+
@decorator
|
| 808 |
+
def raise_value_error(self, item, **kwargs):
|
| 809 |
+
raise ValidationError({"foo": "error"})
|
| 810 |
+
|
| 811 |
+
schema = ExampleSchema()
|
| 812 |
+
with pytest.raises(ValidationError) as exc:
|
| 813 |
+
schema.dump(object())
|
| 814 |
+
assert exc.value.messages == {"foo": "error"}
|
| 815 |
+
schema.load({})
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
class Nested:
|
| 819 |
+
def __init__(self, foo):
|
| 820 |
+
self.foo = foo
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
class Example:
|
| 824 |
+
def __init__(self, nested):
|
| 825 |
+
self.nested = nested
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
example = Example(nested=[Nested(x) for x in range(1)])
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
@pytest.mark.parametrize(
|
| 832 |
+
"data,expected_data,expected_original_data",
|
| 833 |
+
([example, {"foo": 0}, example.nested[0]],),
|
| 834 |
+
)
|
| 835 |
+
def test_decorator_post_dump_with_nested_original_and_pass_many(
|
| 836 |
+
data, expected_data, expected_original_data
|
| 837 |
+
):
|
| 838 |
+
class NestedSchema(Schema):
|
| 839 |
+
foo = fields.Int(required=True)
|
| 840 |
+
|
| 841 |
+
@post_dump(pass_many=False, pass_original=True)
|
| 842 |
+
def check_pass_original_when_pass_many_false(
|
| 843 |
+
self, data, original_data, **kwargs
|
| 844 |
+
):
|
| 845 |
+
assert data == expected_data
|
| 846 |
+
assert original_data == expected_original_data
|
| 847 |
+
return data
|
| 848 |
+
|
| 849 |
+
@post_dump(pass_many=True, pass_original=True)
|
| 850 |
+
def check_pass_original_when_pass_many_true(
|
| 851 |
+
self, data, original_data, many, **kwargs
|
| 852 |
+
):
|
| 853 |
+
assert many is True
|
| 854 |
+
assert data == [expected_data]
|
| 855 |
+
assert original_data == [expected_original_data]
|
| 856 |
+
return data
|
| 857 |
+
|
| 858 |
+
class ExampleSchema(Schema):
|
| 859 |
+
nested = fields.Nested(NestedSchema, required=True, many=True)
|
| 860 |
+
|
| 861 |
+
schema = ExampleSchema()
|
| 862 |
+
assert schema.dump(data) == {"nested": [{"foo": 0}]}
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
@pytest.mark.parametrize(
|
| 866 |
+
"data,expected_data,expected_original_data",
|
| 867 |
+
([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],),
|
| 868 |
+
)
|
| 869 |
+
def test_decorator_post_load_with_nested_original_and_pass_many(
|
| 870 |
+
data, expected_data, expected_original_data
|
| 871 |
+
):
|
| 872 |
+
class NestedSchema(Schema):
|
| 873 |
+
foo = fields.Int(required=True)
|
| 874 |
+
|
| 875 |
+
@post_load(pass_many=False, pass_original=True)
|
| 876 |
+
def check_pass_original_when_pass_many_false(
|
| 877 |
+
self, data, original_data, **kwargs
|
| 878 |
+
):
|
| 879 |
+
assert data == expected_data
|
| 880 |
+
assert original_data == expected_original_data
|
| 881 |
+
return data
|
| 882 |
+
|
| 883 |
+
@post_load(pass_many=True, pass_original=True)
|
| 884 |
+
def check_pass_original_when_pass_many_true(
|
| 885 |
+
self, data, original_data, many, **kwargs
|
| 886 |
+
):
|
| 887 |
+
assert many is True
|
| 888 |
+
assert data == [expected_data]
|
| 889 |
+
assert original_data == [expected_original_data]
|
| 890 |
+
return data
|
| 891 |
+
|
| 892 |
+
class ExampleSchema(Schema):
|
| 893 |
+
nested = fields.Nested(NestedSchema, required=True, many=True)
|
| 894 |
+
|
| 895 |
+
schema = ExampleSchema()
|
| 896 |
+
assert schema.load(data) == data
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_deserialization.py
ADDED
|
@@ -0,0 +1,2298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.mock import patch
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate
|
| 11 |
+
from marshmallow.exceptions import ValidationError
|
| 12 |
+
from marshmallow.validate import Equal
|
| 13 |
+
from tests.base import (
|
| 14 |
+
ALL_FIELDS,
|
| 15 |
+
DateEnum,
|
| 16 |
+
GenderEnum,
|
| 17 |
+
HairColorEnum,
|
| 18 |
+
assert_date_equal,
|
| 19 |
+
assert_time_equal,
|
| 20 |
+
central,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class MockDateTimeOverflowError(dt.datetime):
|
| 25 |
+
"""Used to simulate the possible OverflowError of datetime.fromtimestamp"""
|
| 26 |
+
|
| 27 |
+
def fromtimestamp(self, *args, **kwargs):
|
| 28 |
+
raise OverflowError()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class MockDateTimeOSError(dt.datetime):
|
| 32 |
+
"""Used to simulate the possible OSError of datetime.fromtimestamp"""
|
| 33 |
+
|
| 34 |
+
def fromtimestamp(self, *args, **kwargs):
|
| 35 |
+
raise OSError()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestDeserializingNone:
|
| 39 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 40 |
+
def test_fields_allow_none_deserialize_to_none(self, FieldClass):
|
| 41 |
+
field = FieldClass(allow_none=True)
|
| 42 |
+
assert field.deserialize(None) is None
|
| 43 |
+
|
| 44 |
+
# https://github.com/marshmallow-code/marshmallow/issues/111
|
| 45 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 46 |
+
def test_fields_dont_allow_none_by_default(self, FieldClass):
|
| 47 |
+
field = FieldClass()
|
| 48 |
+
with pytest.raises(ValidationError, match="Field may not be null."):
|
| 49 |
+
field.deserialize(None)
|
| 50 |
+
|
| 51 |
+
def test_allow_none_is_true_if_missing_is_true(self):
|
| 52 |
+
field = fields.Field(load_default=None)
|
| 53 |
+
assert field.allow_none is True
|
| 54 |
+
assert field.deserialize(None) is None
|
| 55 |
+
|
| 56 |
+
def test_list_field_deserialize_none_to_none(self):
|
| 57 |
+
field = fields.List(fields.String(allow_none=True), allow_none=True)
|
| 58 |
+
assert field.deserialize(None) is None
|
| 59 |
+
|
| 60 |
+
def test_tuple_field_deserialize_none_to_none(self):
|
| 61 |
+
field = fields.Tuple([fields.String()], allow_none=True)
|
| 62 |
+
assert field.deserialize(None) is None
|
| 63 |
+
|
| 64 |
+
def test_list_of_nested_allow_none_deserialize_none_to_none(self):
|
| 65 |
+
field = fields.List(fields.Nested(Schema(), allow_none=True))
|
| 66 |
+
assert field.deserialize([None]) == [None]
|
| 67 |
+
|
| 68 |
+
def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self):
|
| 69 |
+
field = fields.List(fields.Nested(Schema(), allow_none=False))
|
| 70 |
+
with pytest.raises(ValidationError):
|
| 71 |
+
field.deserialize([None])
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class TestFieldDeserialization:
|
| 75 |
+
def test_float_field_deserialization(self):
|
| 76 |
+
field = fields.Float()
|
| 77 |
+
assert math.isclose(field.deserialize("12.3"), 12.3)
|
| 78 |
+
assert math.isclose(field.deserialize(12.3), 12.3)
|
| 79 |
+
|
| 80 |
+
@pytest.mark.parametrize("in_val", ["bad", "", {}, True, False])
|
| 81 |
+
def test_invalid_float_field_deserialization(self, in_val):
|
| 82 |
+
field = fields.Float()
|
| 83 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 84 |
+
field.deserialize(in_val)
|
| 85 |
+
assert excinfo.value.args[0] == "Not a valid number."
|
| 86 |
+
|
| 87 |
+
def test_float_field_overflow(self):
|
| 88 |
+
field = fields.Float()
|
| 89 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 90 |
+
field.deserialize(2**1024)
|
| 91 |
+
assert excinfo.value.args[0] == "Number too large."
|
| 92 |
+
|
| 93 |
+
def test_integer_field_deserialization(self):
|
| 94 |
+
field = fields.Integer()
|
| 95 |
+
assert field.deserialize("42") == 42
|
| 96 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 97 |
+
field.deserialize("42.0")
|
| 98 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 99 |
+
with pytest.raises(ValidationError):
|
| 100 |
+
field.deserialize("bad")
|
| 101 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 102 |
+
with pytest.raises(ValidationError):
|
| 103 |
+
field.deserialize({})
|
| 104 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 105 |
+
|
| 106 |
+
def test_strict_integer_field_deserialization(self):
|
| 107 |
+
field = fields.Integer(strict=True)
|
| 108 |
+
assert field.deserialize(42) == 42
|
| 109 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 110 |
+
field.deserialize(42.0)
|
| 111 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 112 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 113 |
+
field.deserialize(decimal.Decimal("42.0"))
|
| 114 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 115 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 116 |
+
field.deserialize("42")
|
| 117 |
+
assert excinfo.value.args[0] == "Not a valid integer."
|
| 118 |
+
|
| 119 |
+
def test_decimal_field_deserialization(self):
|
| 120 |
+
m1 = 12
|
| 121 |
+
m2 = "12.355"
|
| 122 |
+
m3 = decimal.Decimal(1)
|
| 123 |
+
m4 = 3.14
|
| 124 |
+
m5 = "abc"
|
| 125 |
+
m6 = [1, 2]
|
| 126 |
+
|
| 127 |
+
field = fields.Decimal()
|
| 128 |
+
assert isinstance(field.deserialize(m1), decimal.Decimal)
|
| 129 |
+
assert field.deserialize(m1) == decimal.Decimal(12)
|
| 130 |
+
assert isinstance(field.deserialize(m2), decimal.Decimal)
|
| 131 |
+
assert field.deserialize(m2) == decimal.Decimal("12.355")
|
| 132 |
+
assert isinstance(field.deserialize(m3), decimal.Decimal)
|
| 133 |
+
assert field.deserialize(m3) == decimal.Decimal(1)
|
| 134 |
+
assert isinstance(field.deserialize(m4), decimal.Decimal)
|
| 135 |
+
assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2)
|
| 136 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 137 |
+
field.deserialize(m5)
|
| 138 |
+
assert excinfo.value.args[0] == "Not a valid number."
|
| 139 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 140 |
+
field.deserialize(m6)
|
| 141 |
+
assert excinfo.value.args[0] == "Not a valid number."
|
| 142 |
+
|
| 143 |
+
def test_decimal_field_with_places(self):
|
| 144 |
+
m1 = 12
|
| 145 |
+
m2 = "12.355"
|
| 146 |
+
m3 = decimal.Decimal(1)
|
| 147 |
+
m4 = "abc"
|
| 148 |
+
m5 = [1, 2]
|
| 149 |
+
|
| 150 |
+
field = fields.Decimal(1)
|
| 151 |
+
assert isinstance(field.deserialize(m1), decimal.Decimal)
|
| 152 |
+
assert field.deserialize(m1) == decimal.Decimal(12)
|
| 153 |
+
assert isinstance(field.deserialize(m2), decimal.Decimal)
|
| 154 |
+
assert field.deserialize(m2) == decimal.Decimal("12.4")
|
| 155 |
+
assert isinstance(field.deserialize(m3), decimal.Decimal)
|
| 156 |
+
assert field.deserialize(m3) == decimal.Decimal(1)
|
| 157 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 158 |
+
field.deserialize(m4)
|
| 159 |
+
assert excinfo.value.args[0] == "Not a valid number."
|
| 160 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 161 |
+
field.deserialize(m5)
|
| 162 |
+
assert excinfo.value.args[0] == "Not a valid number."
|
| 163 |
+
|
| 164 |
+
def test_decimal_field_with_places_and_rounding(self):
|
| 165 |
+
m1 = 12
|
| 166 |
+
m2 = "12.355"
|
| 167 |
+
m3 = decimal.Decimal(1)
|
| 168 |
+
m4 = "abc"
|
| 169 |
+
m5 = [1, 2]
|
| 170 |
+
|
| 171 |
+
field = fields.Decimal(1, decimal.ROUND_DOWN)
|
| 172 |
+
assert isinstance(field.deserialize(m1), decimal.Decimal)
|
| 173 |
+
assert field.deserialize(m1) == decimal.Decimal(12)
|
| 174 |
+
assert isinstance(field.deserialize(m2), decimal.Decimal)
|
| 175 |
+
assert field.deserialize(m2) == decimal.Decimal("12.3")
|
| 176 |
+
assert isinstance(field.deserialize(m3), decimal.Decimal)
|
| 177 |
+
assert field.deserialize(m3) == decimal.Decimal(1)
|
| 178 |
+
with pytest.raises(ValidationError):
|
| 179 |
+
field.deserialize(m4)
|
| 180 |
+
with pytest.raises(ValidationError):
|
| 181 |
+
field.deserialize(m5)
|
| 182 |
+
|
| 183 |
+
def test_decimal_field_deserialization_string(self):
|
| 184 |
+
m1 = 12
|
| 185 |
+
m2 = "12.355"
|
| 186 |
+
m3 = decimal.Decimal(1)
|
| 187 |
+
m4 = "abc"
|
| 188 |
+
m5 = [1, 2]
|
| 189 |
+
|
| 190 |
+
field = fields.Decimal(as_string=True)
|
| 191 |
+
assert isinstance(field.deserialize(m1), decimal.Decimal)
|
| 192 |
+
assert field.deserialize(m1) == decimal.Decimal(12)
|
| 193 |
+
assert isinstance(field.deserialize(m2), decimal.Decimal)
|
| 194 |
+
assert field.deserialize(m2) == decimal.Decimal("12.355")
|
| 195 |
+
assert isinstance(field.deserialize(m3), decimal.Decimal)
|
| 196 |
+
assert field.deserialize(m3) == decimal.Decimal(1)
|
| 197 |
+
with pytest.raises(ValidationError):
|
| 198 |
+
field.deserialize(m4)
|
| 199 |
+
with pytest.raises(ValidationError):
|
| 200 |
+
field.deserialize(m5)
|
| 201 |
+
|
| 202 |
+
def test_decimal_field_special_values(self):
|
| 203 |
+
m1 = "-NaN"
|
| 204 |
+
m2 = "NaN"
|
| 205 |
+
m3 = "-sNaN"
|
| 206 |
+
m4 = "sNaN"
|
| 207 |
+
m5 = "-Infinity"
|
| 208 |
+
m6 = "Infinity"
|
| 209 |
+
m7 = "-0"
|
| 210 |
+
|
| 211 |
+
field = fields.Decimal(places=2, allow_nan=True)
|
| 212 |
+
|
| 213 |
+
m1d = field.deserialize(m1)
|
| 214 |
+
assert isinstance(m1d, decimal.Decimal)
|
| 215 |
+
assert m1d.is_qnan() and not m1d.is_signed()
|
| 216 |
+
|
| 217 |
+
m2d = field.deserialize(m2)
|
| 218 |
+
assert isinstance(m2d, decimal.Decimal)
|
| 219 |
+
assert m2d.is_qnan() and not m2d.is_signed()
|
| 220 |
+
|
| 221 |
+
m3d = field.deserialize(m3)
|
| 222 |
+
assert isinstance(m3d, decimal.Decimal)
|
| 223 |
+
assert m3d.is_qnan() and not m3d.is_signed()
|
| 224 |
+
|
| 225 |
+
m4d = field.deserialize(m4)
|
| 226 |
+
assert isinstance(m4d, decimal.Decimal)
|
| 227 |
+
assert m4d.is_qnan() and not m4d.is_signed()
|
| 228 |
+
|
| 229 |
+
m5d = field.deserialize(m5)
|
| 230 |
+
assert isinstance(m5d, decimal.Decimal)
|
| 231 |
+
assert m5d.is_infinite() and m5d.is_signed()
|
| 232 |
+
|
| 233 |
+
m6d = field.deserialize(m6)
|
| 234 |
+
assert isinstance(m6d, decimal.Decimal)
|
| 235 |
+
assert m6d.is_infinite() and not m6d.is_signed()
|
| 236 |
+
|
| 237 |
+
m7d = field.deserialize(m7)
|
| 238 |
+
assert isinstance(m7d, decimal.Decimal)
|
| 239 |
+
assert m7d.is_zero() and m7d.is_signed()
|
| 240 |
+
|
| 241 |
+
def test_decimal_field_special_values_not_permitted(self):
|
| 242 |
+
m1 = "-NaN"
|
| 243 |
+
m2 = "NaN"
|
| 244 |
+
m3 = "-sNaN"
|
| 245 |
+
m4 = "sNaN"
|
| 246 |
+
m5 = "-Infinity"
|
| 247 |
+
m6 = "Infinity"
|
| 248 |
+
m7 = "-0"
|
| 249 |
+
|
| 250 |
+
field = fields.Decimal(places=2)
|
| 251 |
+
|
| 252 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 253 |
+
field.deserialize(m1)
|
| 254 |
+
assert str(excinfo.value.args[0]) == (
|
| 255 |
+
"Special numeric values (nan or infinity) are not permitted."
|
| 256 |
+
)
|
| 257 |
+
with pytest.raises(ValidationError):
|
| 258 |
+
field.deserialize(m2)
|
| 259 |
+
with pytest.raises(ValidationError):
|
| 260 |
+
field.deserialize(m3)
|
| 261 |
+
with pytest.raises(ValidationError):
|
| 262 |
+
field.deserialize(m4)
|
| 263 |
+
with pytest.raises(ValidationError):
|
| 264 |
+
field.deserialize(m5)
|
| 265 |
+
with pytest.raises(ValidationError):
|
| 266 |
+
field.deserialize(m6)
|
| 267 |
+
|
| 268 |
+
m7d = field.deserialize(m7)
|
| 269 |
+
assert isinstance(m7d, decimal.Decimal)
|
| 270 |
+
assert m7d.is_zero() and m7d.is_signed()
|
| 271 |
+
|
| 272 |
+
@pytest.mark.parametrize("allow_nan", (None, False, True))
|
| 273 |
+
@pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf"))
|
| 274 |
+
def test_float_field_allow_nan(self, value, allow_nan):
|
| 275 |
+
if allow_nan is None:
|
| 276 |
+
# Test default case is False
|
| 277 |
+
field = fields.Float()
|
| 278 |
+
else:
|
| 279 |
+
field = fields.Float(allow_nan=allow_nan)
|
| 280 |
+
|
| 281 |
+
if allow_nan is True:
|
| 282 |
+
res = field.deserialize(value)
|
| 283 |
+
assert isinstance(res, float)
|
| 284 |
+
if value.endswith("nan"):
|
| 285 |
+
assert math.isnan(res)
|
| 286 |
+
else:
|
| 287 |
+
assert res == float(value)
|
| 288 |
+
else:
|
| 289 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 290 |
+
field.deserialize(value)
|
| 291 |
+
assert str(excinfo.value.args[0]) == (
|
| 292 |
+
"Special numeric values (nan or infinity) are not permitted."
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
def test_string_field_deserialization(self):
|
| 296 |
+
field = fields.String()
|
| 297 |
+
assert field.deserialize("foo") == "foo"
|
| 298 |
+
assert field.deserialize(b"foo") == "foo"
|
| 299 |
+
|
| 300 |
+
# https://github.com/marshmallow-code/marshmallow/issues/231
|
| 301 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 302 |
+
field.deserialize(42)
|
| 303 |
+
assert excinfo.value.args[0] == "Not a valid string."
|
| 304 |
+
|
| 305 |
+
with pytest.raises(ValidationError):
|
| 306 |
+
field.deserialize({})
|
| 307 |
+
|
| 308 |
+
def test_boolean_field_deserialization(self):
|
| 309 |
+
field = fields.Boolean()
|
| 310 |
+
assert field.deserialize(True) is True
|
| 311 |
+
assert field.deserialize(False) is False
|
| 312 |
+
assert field.deserialize("True") is True
|
| 313 |
+
assert field.deserialize("False") is False
|
| 314 |
+
assert field.deserialize("true") is True
|
| 315 |
+
assert field.deserialize("false") is False
|
| 316 |
+
assert field.deserialize("1") is True
|
| 317 |
+
assert field.deserialize("0") is False
|
| 318 |
+
assert field.deserialize("on") is True
|
| 319 |
+
assert field.deserialize("ON") is True
|
| 320 |
+
assert field.deserialize("On") is True
|
| 321 |
+
assert field.deserialize("off") is False
|
| 322 |
+
assert field.deserialize("OFF") is False
|
| 323 |
+
assert field.deserialize("Off") is False
|
| 324 |
+
assert field.deserialize("y") is True
|
| 325 |
+
assert field.deserialize("Y") is True
|
| 326 |
+
assert field.deserialize("yes") is True
|
| 327 |
+
assert field.deserialize("YES") is True
|
| 328 |
+
assert field.deserialize("Yes") is True
|
| 329 |
+
assert field.deserialize("n") is False
|
| 330 |
+
assert field.deserialize("N") is False
|
| 331 |
+
assert field.deserialize("no") is False
|
| 332 |
+
assert field.deserialize("NO") is False
|
| 333 |
+
assert field.deserialize("No") is False
|
| 334 |
+
assert field.deserialize(1) is True
|
| 335 |
+
assert field.deserialize(0) is False
|
| 336 |
+
|
| 337 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 338 |
+
field.deserialize({})
|
| 339 |
+
assert excinfo.value.args[0] == "Not a valid boolean."
|
| 340 |
+
|
| 341 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 342 |
+
field.deserialize(42)
|
| 343 |
+
|
| 344 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 345 |
+
field.deserialize("invalid-string")
|
| 346 |
+
|
| 347 |
+
def test_boolean_field_deserialization_with_custom_truthy_values(self):
|
| 348 |
+
class MyBoolean(fields.Boolean):
|
| 349 |
+
truthy = {"yep"}
|
| 350 |
+
|
| 351 |
+
field = MyBoolean()
|
| 352 |
+
assert field.deserialize("yep") is True
|
| 353 |
+
|
| 354 |
+
field = fields.Boolean(truthy=("yep",))
|
| 355 |
+
assert field.deserialize("yep") is True
|
| 356 |
+
assert field.deserialize(False) is False
|
| 357 |
+
|
| 358 |
+
@pytest.mark.parametrize("in_val", ["notvalid", 123])
|
| 359 |
+
def test_boolean_field_deserialization_with_custom_truthy_values_invalid(
|
| 360 |
+
self, in_val
|
| 361 |
+
):
|
| 362 |
+
class MyBoolean(fields.Boolean):
|
| 363 |
+
truthy = {"yep"}
|
| 364 |
+
|
| 365 |
+
field = MyBoolean()
|
| 366 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 367 |
+
field.deserialize(in_val)
|
| 368 |
+
expected_msg = "Not a valid boolean."
|
| 369 |
+
assert str(excinfo.value.args[0]) == expected_msg
|
| 370 |
+
|
| 371 |
+
field = fields.Boolean(truthy=("yep",))
|
| 372 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 373 |
+
field.deserialize(in_val)
|
| 374 |
+
expected_msg = "Not a valid boolean."
|
| 375 |
+
assert str(excinfo.value.args[0]) == expected_msg
|
| 376 |
+
|
| 377 |
+
field2 = MyBoolean(error_messages={"invalid": "bad input"})
|
| 378 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 379 |
+
field2.deserialize(in_val)
|
| 380 |
+
assert str(excinfo.value.args[0]) == "bad input"
|
| 381 |
+
|
| 382 |
+
field2 = fields.Boolean(
|
| 383 |
+
truthy=("yep",), error_messages={"invalid": "bad input"}
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
def test_boolean_field_deserialization_with_empty_truthy(self):
|
| 387 |
+
field = fields.Boolean(truthy=())
|
| 388 |
+
assert field.deserialize("yep") is True
|
| 389 |
+
assert field.deserialize(True) is True
|
| 390 |
+
assert field.deserialize(False) is False
|
| 391 |
+
|
| 392 |
+
def test_boolean_field_deserialization_with_custom_falsy_values(self):
|
| 393 |
+
field = fields.Boolean(falsy=("nope",))
|
| 394 |
+
assert field.deserialize("nope") is False
|
| 395 |
+
assert field.deserialize(True) is True
|
| 396 |
+
|
| 397 |
+
def test_field_toggle_show_invalid_value_in_error_message(self):
|
| 398 |
+
error_messages = {"invalid": "Not valid: {input}"}
|
| 399 |
+
boolfield = fields.Boolean(error_messages=error_messages)
|
| 400 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 401 |
+
boolfield.deserialize("notabool")
|
| 402 |
+
assert str(excinfo.value.args[0]) == "Not valid: notabool"
|
| 403 |
+
|
| 404 |
+
numfield = fields.Number(error_messages=error_messages)
|
| 405 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 406 |
+
numfield.deserialize("notanum")
|
| 407 |
+
assert str(excinfo.value.args[0]) == "Not valid: notanum"
|
| 408 |
+
|
| 409 |
+
intfield = fields.Integer(error_messages=error_messages)
|
| 410 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 411 |
+
intfield.deserialize("notanint")
|
| 412 |
+
assert str(excinfo.value.args[0]) == "Not valid: notanint"
|
| 413 |
+
|
| 414 |
+
date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"}
|
| 415 |
+
datefield = fields.DateTime(error_messages=date_error_messages)
|
| 416 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 417 |
+
datefield.deserialize("notadate")
|
| 418 |
+
assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate"
|
| 419 |
+
|
| 420 |
+
@pytest.mark.parametrize(
|
| 421 |
+
"in_value",
|
| 422 |
+
[
|
| 423 |
+
"not-a-datetime",
|
| 424 |
+
42,
|
| 425 |
+
True,
|
| 426 |
+
False,
|
| 427 |
+
0,
|
| 428 |
+
"",
|
| 429 |
+
[],
|
| 430 |
+
"2018",
|
| 431 |
+
"2018-01-01",
|
| 432 |
+
dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"),
|
| 433 |
+
dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"),
|
| 434 |
+
],
|
| 435 |
+
)
|
| 436 |
+
def test_invalid_datetime_deserialization(self, in_value):
|
| 437 |
+
field = fields.DateTime()
|
| 438 |
+
with pytest.raises(ValidationError, match="Not a valid datetime."):
|
| 439 |
+
field.deserialize(in_value)
|
| 440 |
+
|
| 441 |
+
def test_custom_date_format_datetime_field_deserialization(self):
|
| 442 |
+
# Datetime string with format "%H:%M:%S.%f %Y-%m-%d"
|
| 443 |
+
datestring = "10:11:12.123456 2019-01-02"
|
| 444 |
+
|
| 445 |
+
# Deserialization should fail when datestring is not of same format
|
| 446 |
+
field = fields.DateTime(format="%d-%m-%Y %H:%M:%S")
|
| 447 |
+
with pytest.raises(ValidationError, match="Not a valid datetime."):
|
| 448 |
+
field.deserialize(datestring)
|
| 449 |
+
|
| 450 |
+
field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d")
|
| 451 |
+
assert field.deserialize(datestring) == dt.datetime(
|
| 452 |
+
2019, 1, 2, 10, 11, 12, 123456
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d")
|
| 456 |
+
assert field.deserialize(datestring) == dt.datetime(
|
| 457 |
+
2019, 1, 2, 10, 11, 12, 123456
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d")
|
| 461 |
+
with pytest.raises(ValidationError, match="Not a valid aware datetime."):
|
| 462 |
+
field.deserialize(datestring)
|
| 463 |
+
|
| 464 |
+
@pytest.mark.parametrize("fmt", ["rfc", "rfc822"])
|
| 465 |
+
@pytest.mark.parametrize(
|
| 466 |
+
("value", "expected", "aware"),
|
| 467 |
+
[
|
| 468 |
+
(
|
| 469 |
+
"Sun, 10 Nov 2013 01:23:45 -0000",
|
| 470 |
+
dt.datetime(2013, 11, 10, 1, 23, 45),
|
| 471 |
+
False,
|
| 472 |
+
),
|
| 473 |
+
(
|
| 474 |
+
"Sun, 10 Nov 2013 01:23:45 +0000",
|
| 475 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
|
| 476 |
+
True,
|
| 477 |
+
),
|
| 478 |
+
(
|
| 479 |
+
"Sun, 10 Nov 2013 01:23:45 -0600",
|
| 480 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central),
|
| 481 |
+
True,
|
| 482 |
+
),
|
| 483 |
+
],
|
| 484 |
+
)
|
| 485 |
+
def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware):
|
| 486 |
+
field = fields.DateTime(format=fmt)
|
| 487 |
+
assert field.deserialize(value) == expected
|
| 488 |
+
field = fields.NaiveDateTime(format=fmt)
|
| 489 |
+
if aware:
|
| 490 |
+
with pytest.raises(ValidationError, match="Not a valid naive datetime."):
|
| 491 |
+
field.deserialize(value)
|
| 492 |
+
else:
|
| 493 |
+
assert field.deserialize(value) == expected
|
| 494 |
+
field = fields.AwareDateTime(format=fmt)
|
| 495 |
+
if not aware:
|
| 496 |
+
with pytest.raises(ValidationError, match="Not a valid aware datetime."):
|
| 497 |
+
field.deserialize(value)
|
| 498 |
+
else:
|
| 499 |
+
assert field.deserialize(value) == expected
|
| 500 |
+
|
| 501 |
+
@pytest.mark.parametrize("fmt", ["iso", "iso8601"])
|
| 502 |
+
@pytest.mark.parametrize(
|
| 503 |
+
("value", "expected", "aware"),
|
| 504 |
+
[
|
| 505 |
+
("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False),
|
| 506 |
+
(
|
| 507 |
+
"2013-11-10T01:23:45+00:00",
|
| 508 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
|
| 509 |
+
True,
|
| 510 |
+
),
|
| 511 |
+
(
|
| 512 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251
|
| 513 |
+
"2013-11-10T01:23:45.123+00:00",
|
| 514 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc),
|
| 515 |
+
True,
|
| 516 |
+
),
|
| 517 |
+
(
|
| 518 |
+
"2013-11-10T01:23:45.123456+00:00",
|
| 519 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc),
|
| 520 |
+
True,
|
| 521 |
+
),
|
| 522 |
+
(
|
| 523 |
+
"2013-11-10T01:23:45-06:00",
|
| 524 |
+
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central),
|
| 525 |
+
True,
|
| 526 |
+
),
|
| 527 |
+
],
|
| 528 |
+
)
|
| 529 |
+
def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware):
|
| 530 |
+
field = fields.DateTime(format=fmt)
|
| 531 |
+
assert field.deserialize(value) == expected
|
| 532 |
+
field = fields.NaiveDateTime(format=fmt)
|
| 533 |
+
if aware:
|
| 534 |
+
with pytest.raises(ValidationError, match="Not a valid naive datetime."):
|
| 535 |
+
field.deserialize(value)
|
| 536 |
+
else:
|
| 537 |
+
assert field.deserialize(value) == expected
|
| 538 |
+
field = fields.AwareDateTime(format=fmt)
|
| 539 |
+
if not aware:
|
| 540 |
+
with pytest.raises(ValidationError, match="Not a valid aware datetime."):
|
| 541 |
+
field.deserialize(value)
|
| 542 |
+
else:
|
| 543 |
+
assert field.deserialize(value) == expected
|
| 544 |
+
|
| 545 |
+
@pytest.mark.parametrize(
|
| 546 |
+
("fmt", "value", "expected"),
|
| 547 |
+
[
|
| 548 |
+
("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)),
|
| 549 |
+
("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)),
|
| 550 |
+
("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)),
|
| 551 |
+
("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)),
|
| 552 |
+
(
|
| 553 |
+
"timestamp",
|
| 554 |
+
1384043025.123456,
|
| 555 |
+
dt.datetime(2013, 11, 10, 0, 23, 45, 123456),
|
| 556 |
+
),
|
| 557 |
+
("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)),
|
| 558 |
+
("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)),
|
| 559 |
+
("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)),
|
| 560 |
+
],
|
| 561 |
+
)
|
| 562 |
+
def test_timestamp_field_deserialization(self, fmt, value, expected):
|
| 563 |
+
field = fields.DateTime(format=fmt)
|
| 564 |
+
assert field.deserialize(value) == expected
|
| 565 |
+
|
| 566 |
+
# By default, a datetime from a timestamp is never aware.
|
| 567 |
+
field = fields.NaiveDateTime(format=fmt)
|
| 568 |
+
assert field.deserialize(value) == expected
|
| 569 |
+
|
| 570 |
+
field = fields.AwareDateTime(format=fmt)
|
| 571 |
+
with pytest.raises(ValidationError, match="Not a valid aware datetime."):
|
| 572 |
+
field.deserialize(value)
|
| 573 |
+
|
| 574 |
+
# But it can be added by providing a default.
|
| 575 |
+
field = fields.AwareDateTime(format=fmt, default_timezone=central)
|
| 576 |
+
expected_aware = expected.replace(tzinfo=central)
|
| 577 |
+
assert field.deserialize(value) == expected_aware
|
| 578 |
+
|
| 579 |
+
@pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"])
|
| 580 |
+
@pytest.mark.parametrize(
|
| 581 |
+
"in_value",
|
| 582 |
+
["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)],
|
| 583 |
+
)
|
| 584 |
+
def test_invalid_timestamp_field_deserialization(self, fmt, in_value):
|
| 585 |
+
field = fields.DateTime(format=fmt)
|
| 586 |
+
with pytest.raises(ValidationError, match="Not a valid datetime."):
|
| 587 |
+
field.deserialize(in_value)
|
| 588 |
+
|
| 589 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102
|
| 590 |
+
@pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"])
|
| 591 |
+
@pytest.mark.parametrize(
|
| 592 |
+
"mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError]
|
| 593 |
+
)
|
| 594 |
+
def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp):
|
| 595 |
+
with patch("datetime.datetime", mock_fromtimestamp):
|
| 596 |
+
field = fields.DateTime(format=fmt)
|
| 597 |
+
with pytest.raises(ValidationError, match="Not a valid datetime."):
|
| 598 |
+
field.deserialize(99999999999999999)
|
| 599 |
+
|
| 600 |
+
@pytest.mark.parametrize(
|
| 601 |
+
("fmt", "timezone", "value", "expected"),
|
| 602 |
+
[
|
| 603 |
+
("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)),
|
| 604 |
+
(
|
| 605 |
+
"iso",
|
| 606 |
+
dt.timezone.utc,
|
| 607 |
+
"2013-11-10T01:23:45+00:00",
|
| 608 |
+
dt.datetime(2013, 11, 10, 1, 23, 45),
|
| 609 |
+
),
|
| 610 |
+
(
|
| 611 |
+
"iso",
|
| 612 |
+
central,
|
| 613 |
+
"2013-11-10T01:23:45-03:00",
|
| 614 |
+
dt.datetime(2013, 11, 9, 22, 23, 45),
|
| 615 |
+
),
|
| 616 |
+
(
|
| 617 |
+
"rfc",
|
| 618 |
+
None,
|
| 619 |
+
"Sun, 10 Nov 2013 01:23:45 -0000",
|
| 620 |
+
dt.datetime(2013, 11, 10, 1, 23, 45),
|
| 621 |
+
),
|
| 622 |
+
(
|
| 623 |
+
"rfc",
|
| 624 |
+
dt.timezone.utc,
|
| 625 |
+
"Sun, 10 Nov 2013 01:23:45 +0000",
|
| 626 |
+
dt.datetime(2013, 11, 10, 1, 23, 45),
|
| 627 |
+
),
|
| 628 |
+
(
|
| 629 |
+
"rfc",
|
| 630 |
+
central,
|
| 631 |
+
"Sun, 10 Nov 2013 01:23:45 -0300",
|
| 632 |
+
dt.datetime(2013, 11, 9, 22, 23, 45),
|
| 633 |
+
),
|
| 634 |
+
],
|
| 635 |
+
)
|
| 636 |
+
def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected):
|
| 637 |
+
field = fields.NaiveDateTime(format=fmt, timezone=timezone)
|
| 638 |
+
assert field.deserialize(value) == expected
|
| 639 |
+
|
| 640 |
+
@pytest.mark.parametrize("timezone", (dt.timezone.utc, central))
|
| 641 |
+
@pytest.mark.parametrize(
|
| 642 |
+
("fmt", "value"),
|
| 643 |
+
[("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")],
|
| 644 |
+
)
|
| 645 |
+
def test_aware_datetime_default_timezone(self, fmt, timezone, value):
|
| 646 |
+
field = fields.AwareDateTime(format=fmt, default_timezone=timezone)
|
| 647 |
+
assert field.deserialize(value) == dt.datetime(
|
| 648 |
+
2013, 11, 10, 1, 23, 45, tzinfo=timezone
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
def test_time_field_deserialization(self):
|
| 652 |
+
field = fields.Time()
|
| 653 |
+
t = dt.time(1, 23, 45)
|
| 654 |
+
t_formatted = t.isoformat()
|
| 655 |
+
result = field.deserialize(t_formatted)
|
| 656 |
+
assert isinstance(result, dt.time)
|
| 657 |
+
assert_time_equal(result, t)
|
| 658 |
+
# With microseconds
|
| 659 |
+
t2 = dt.time(1, 23, 45, 6789)
|
| 660 |
+
t2_formatted = t2.isoformat()
|
| 661 |
+
result2 = field.deserialize(t2_formatted)
|
| 662 |
+
assert_time_equal(result2, t2)
|
| 663 |
+
|
| 664 |
+
@pytest.mark.parametrize("in_data", ["badvalue", "", [], 42])
|
| 665 |
+
def test_invalid_time_field_deserialization(self, in_data):
|
| 666 |
+
field = fields.Time()
|
| 667 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 668 |
+
field.deserialize(in_data)
|
| 669 |
+
assert excinfo.value.args[0] == "Not a valid time."
|
| 670 |
+
|
| 671 |
+
def test_custom_time_format_time_field_deserialization(self):
|
| 672 |
+
# Time string with format "%f.%S:%M:%H"
|
| 673 |
+
timestring = "123456.12:11:10"
|
| 674 |
+
|
| 675 |
+
# Deserialization should fail when timestring is not of same format
|
| 676 |
+
field = fields.Time(format="%S:%M:%H")
|
| 677 |
+
with pytest.raises(ValidationError, match="Not a valid time."):
|
| 678 |
+
field.deserialize(timestring)
|
| 679 |
+
|
| 680 |
+
field = fields.Time(format="%f.%S:%M:%H")
|
| 681 |
+
assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456)
|
| 682 |
+
|
| 683 |
+
@pytest.mark.parametrize("fmt", ["iso", "iso8601", None])
|
| 684 |
+
@pytest.mark.parametrize(
|
| 685 |
+
("value", "expected"),
|
| 686 |
+
[
|
| 687 |
+
("01:23:45", dt.time(1, 23, 45)),
|
| 688 |
+
("01:23:45+01:00", dt.time(1, 23, 45)),
|
| 689 |
+
("01:23:45.123", dt.time(1, 23, 45, 123000)),
|
| 690 |
+
("01:23:45.123456", dt.time(1, 23, 45, 123456)),
|
| 691 |
+
],
|
| 692 |
+
)
|
| 693 |
+
def test_iso_time_field_deserialization(self, fmt, value, expected):
|
| 694 |
+
if fmt is None:
|
| 695 |
+
field = fields.Time()
|
| 696 |
+
else:
|
| 697 |
+
field = fields.Time(format=fmt)
|
| 698 |
+
assert field.deserialize(value) == expected
|
| 699 |
+
|
| 700 |
+
def test_invalid_timedelta_precision(self):
|
| 701 |
+
with pytest.raises(ValueError, match='The precision must be "days",'):
|
| 702 |
+
fields.TimeDelta("invalid")
|
| 703 |
+
|
| 704 |
+
def test_timedelta_field_deserialization(self):
|
| 705 |
+
field = fields.TimeDelta()
|
| 706 |
+
result = field.deserialize("42")
|
| 707 |
+
assert isinstance(result, dt.timedelta)
|
| 708 |
+
assert result.days == 0
|
| 709 |
+
assert result.seconds == 42
|
| 710 |
+
assert result.microseconds == 0
|
| 711 |
+
|
| 712 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS)
|
| 713 |
+
result = field.deserialize(100000)
|
| 714 |
+
assert result.days == 1
|
| 715 |
+
assert result.seconds == 13600
|
| 716 |
+
assert result.microseconds == 0
|
| 717 |
+
|
| 718 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS)
|
| 719 |
+
result = field.deserialize("-42")
|
| 720 |
+
assert isinstance(result, dt.timedelta)
|
| 721 |
+
assert result.days == -42
|
| 722 |
+
assert result.seconds == 0
|
| 723 |
+
assert result.microseconds == 0
|
| 724 |
+
|
| 725 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
|
| 726 |
+
result = field.deserialize(10**6 + 1)
|
| 727 |
+
assert isinstance(result, dt.timedelta)
|
| 728 |
+
assert result.days == 0
|
| 729 |
+
assert result.seconds == 1
|
| 730 |
+
assert result.microseconds == 1
|
| 731 |
+
|
| 732 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS)
|
| 733 |
+
result = field.deserialize(86400 * 10**6 + 1)
|
| 734 |
+
assert isinstance(result, dt.timedelta)
|
| 735 |
+
assert result.days == 1
|
| 736 |
+
assert result.seconds == 0
|
| 737 |
+
assert result.microseconds == 1
|
| 738 |
+
|
| 739 |
+
field = fields.TimeDelta()
|
| 740 |
+
result = field.deserialize(12.9)
|
| 741 |
+
assert isinstance(result, dt.timedelta)
|
| 742 |
+
assert result.days == 0
|
| 743 |
+
assert result.seconds == 12
|
| 744 |
+
assert result.microseconds == 0
|
| 745 |
+
|
| 746 |
+
field = fields.TimeDelta(fields.TimeDelta.WEEKS)
|
| 747 |
+
result = field.deserialize(1)
|
| 748 |
+
assert isinstance(result, dt.timedelta)
|
| 749 |
+
assert result.days == 7
|
| 750 |
+
assert result.seconds == 0
|
| 751 |
+
assert result.microseconds == 0
|
| 752 |
+
|
| 753 |
+
field = fields.TimeDelta(fields.TimeDelta.HOURS)
|
| 754 |
+
result = field.deserialize(25)
|
| 755 |
+
assert isinstance(result, dt.timedelta)
|
| 756 |
+
assert result.days == 1
|
| 757 |
+
assert result.seconds == 3600
|
| 758 |
+
assert result.microseconds == 0
|
| 759 |
+
|
| 760 |
+
field = fields.TimeDelta(fields.TimeDelta.MINUTES)
|
| 761 |
+
result = field.deserialize(1441)
|
| 762 |
+
assert isinstance(result, dt.timedelta)
|
| 763 |
+
assert result.days == 1
|
| 764 |
+
assert result.seconds == 60
|
| 765 |
+
assert result.microseconds == 0
|
| 766 |
+
|
| 767 |
+
field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS)
|
| 768 |
+
result = field.deserialize(123456)
|
| 769 |
+
assert isinstance(result, dt.timedelta)
|
| 770 |
+
assert result.days == 0
|
| 771 |
+
assert result.seconds == 123
|
| 772 |
+
assert result.microseconds == 456000
|
| 773 |
+
|
| 774 |
+
total_microseconds_value = 322.0
|
| 775 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float)
|
| 776 |
+
result = field.deserialize(total_microseconds_value)
|
| 777 |
+
assert isinstance(result, dt.timedelta)
|
| 778 |
+
unit_value = dt.timedelta(microseconds=1).total_seconds()
|
| 779 |
+
assert math.isclose(
|
| 780 |
+
result.total_seconds() / unit_value, total_microseconds_value
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
total_microseconds_value = 322.12345
|
| 784 |
+
field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float)
|
| 785 |
+
result = field.deserialize(total_microseconds_value)
|
| 786 |
+
assert isinstance(result, dt.timedelta)
|
| 787 |
+
unit_value = dt.timedelta(microseconds=1).total_seconds()
|
| 788 |
+
assert math.isclose(
|
| 789 |
+
result.total_seconds() / unit_value, math.floor(total_microseconds_value)
|
| 790 |
+
)
|
| 791 |
+
|
| 792 |
+
total_milliseconds_value = 322.223
|
| 793 |
+
field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float)
|
| 794 |
+
result = field.deserialize(total_milliseconds_value)
|
| 795 |
+
assert isinstance(result, dt.timedelta)
|
| 796 |
+
unit_value = dt.timedelta(milliseconds=1).total_seconds()
|
| 797 |
+
assert math.isclose(
|
| 798 |
+
result.total_seconds() / unit_value, total_milliseconds_value
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
total_seconds_value = 322.223
|
| 802 |
+
field = fields.TimeDelta(fields.TimeDelta.SECONDS, float)
|
| 803 |
+
result = field.deserialize(total_seconds_value)
|
| 804 |
+
assert isinstance(result, dt.timedelta)
|
| 805 |
+
assert math.isclose(result.total_seconds(), total_seconds_value)
|
| 806 |
+
|
| 807 |
+
total_minutes_value = 322.223
|
| 808 |
+
field = fields.TimeDelta(fields.TimeDelta.MINUTES, float)
|
| 809 |
+
result = field.deserialize(total_minutes_value)
|
| 810 |
+
assert isinstance(result, dt.timedelta)
|
| 811 |
+
unit_value = dt.timedelta(minutes=1).total_seconds()
|
| 812 |
+
assert math.isclose(result.total_seconds() / unit_value, total_minutes_value)
|
| 813 |
+
|
| 814 |
+
total_hours_value = 322.223
|
| 815 |
+
field = fields.TimeDelta(fields.TimeDelta.HOURS, float)
|
| 816 |
+
result = field.deserialize(total_hours_value)
|
| 817 |
+
assert isinstance(result, dt.timedelta)
|
| 818 |
+
unit_value = dt.timedelta(hours=1).total_seconds()
|
| 819 |
+
assert math.isclose(result.total_seconds() / unit_value, total_hours_value)
|
| 820 |
+
|
| 821 |
+
total_days_value = 322.223
|
| 822 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS, float)
|
| 823 |
+
result = field.deserialize(total_days_value)
|
| 824 |
+
assert isinstance(result, dt.timedelta)
|
| 825 |
+
unit_value = dt.timedelta(days=1).total_seconds()
|
| 826 |
+
assert math.isclose(result.total_seconds() / unit_value, total_days_value)
|
| 827 |
+
|
| 828 |
+
total_weeks_value = 322.223
|
| 829 |
+
field = fields.TimeDelta(fields.TimeDelta.WEEKS, float)
|
| 830 |
+
result = field.deserialize(total_weeks_value)
|
| 831 |
+
assert isinstance(result, dt.timedelta)
|
| 832 |
+
unit_value = dt.timedelta(weeks=1).total_seconds()
|
| 833 |
+
assert math.isclose(result.total_seconds() / unit_value, total_weeks_value)
|
| 834 |
+
|
| 835 |
+
@pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999])
|
| 836 |
+
def test_invalid_timedelta_field_deserialization(self, in_value):
|
| 837 |
+
field = fields.TimeDelta(fields.TimeDelta.DAYS)
|
| 838 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 839 |
+
field.deserialize(in_value)
|
| 840 |
+
assert excinfo.value.args[0] == "Not a valid period of time."
|
| 841 |
+
|
| 842 |
+
@pytest.mark.parametrize("format", (None, "%Y-%m-%d"))
|
| 843 |
+
def test_date_field_deserialization(self, format):
|
| 844 |
+
field = fields.Date(format=format)
|
| 845 |
+
d = dt.date(2014, 8, 21)
|
| 846 |
+
iso_date = d.isoformat()
|
| 847 |
+
result = field.deserialize(iso_date)
|
| 848 |
+
assert type(result) is dt.date
|
| 849 |
+
assert_date_equal(result, d)
|
| 850 |
+
|
| 851 |
+
@pytest.mark.parametrize(
|
| 852 |
+
"in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")]
|
| 853 |
+
)
|
| 854 |
+
def test_invalid_date_field_deserialization(self, in_value):
|
| 855 |
+
field = fields.Date()
|
| 856 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 857 |
+
field.deserialize(in_value)
|
| 858 |
+
msg = "Not a valid date."
|
| 859 |
+
assert excinfo.value.args[0] == msg
|
| 860 |
+
|
| 861 |
+
def test_dict_field_deserialization(self):
|
| 862 |
+
data = {"foo": "bar"}
|
| 863 |
+
field = fields.Dict()
|
| 864 |
+
load = field.deserialize(data)
|
| 865 |
+
assert load == {"foo": "bar"}
|
| 866 |
+
# Check load is a distinct object
|
| 867 |
+
load["foo"] = "baz"
|
| 868 |
+
assert data["foo"] == "bar"
|
| 869 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 870 |
+
field.deserialize("baddict")
|
| 871 |
+
assert excinfo.value.args[0] == "Not a valid mapping type."
|
| 872 |
+
|
| 873 |
+
def test_structured_dict_value_deserialization(self):
|
| 874 |
+
field = fields.Dict(values=fields.List(fields.Str))
|
| 875 |
+
assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]}
|
| 876 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 877 |
+
field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]})
|
| 878 |
+
assert excinfo.value.args[0] == {
|
| 879 |
+
"foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}},
|
| 880 |
+
"bar": {"value": ["Not a valid list."]},
|
| 881 |
+
}
|
| 882 |
+
assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]}
|
| 883 |
+
|
| 884 |
+
def test_structured_dict_key_deserialization(self):
|
| 885 |
+
field = fields.Dict(keys=fields.Str)
|
| 886 |
+
assert field.deserialize({"foo": "bar"}) == {"foo": "bar"}
|
| 887 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 888 |
+
field.deserialize({1: "bar", "foo": "baz"})
|
| 889 |
+
assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}}
|
| 890 |
+
assert excinfo.value.valid_data == {"foo": "baz"}
|
| 891 |
+
|
| 892 |
+
def test_structured_dict_key_value_deserialization(self):
|
| 893 |
+
field = fields.Dict(
|
| 894 |
+
keys=fields.Str(
|
| 895 |
+
validate=[validate.Email(), validate.Regexp(r".*@test\.com$")]
|
| 896 |
+
),
|
| 897 |
+
values=fields.Decimal,
|
| 898 |
+
)
|
| 899 |
+
assert field.deserialize({"foo@test.com": 1}) == {
|
| 900 |
+
"foo@test.com": decimal.Decimal(1)
|
| 901 |
+
}
|
| 902 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 903 |
+
field.deserialize({1: "bar"})
|
| 904 |
+
assert excinfo.value.args[0] == {
|
| 905 |
+
1: {"key": ["Not a valid string."], "value": ["Not a valid number."]}
|
| 906 |
+
}
|
| 907 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 908 |
+
field.deserialize({"foo@test.com": "bar"})
|
| 909 |
+
assert excinfo.value.args[0] == {
|
| 910 |
+
"foo@test.com": {"value": ["Not a valid number."]}
|
| 911 |
+
}
|
| 912 |
+
assert excinfo.value.valid_data == {}
|
| 913 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 914 |
+
field.deserialize({1: 1})
|
| 915 |
+
assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}}
|
| 916 |
+
assert excinfo.value.valid_data == {}
|
| 917 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 918 |
+
field.deserialize({"foo": "bar"})
|
| 919 |
+
assert excinfo.value.args[0] == {
|
| 920 |
+
"foo": {
|
| 921 |
+
"key": [
|
| 922 |
+
"Not a valid email address.",
|
| 923 |
+
"String does not match expected pattern.",
|
| 924 |
+
],
|
| 925 |
+
"value": ["Not a valid number."],
|
| 926 |
+
}
|
| 927 |
+
}
|
| 928 |
+
assert excinfo.value.valid_data == {}
|
| 929 |
+
|
| 930 |
+
def test_url_field_deserialization(self):
|
| 931 |
+
field = fields.Url()
|
| 932 |
+
assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com"
|
| 933 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 934 |
+
field.deserialize("badurl")
|
| 935 |
+
assert excinfo.value.args[0][0] == "Not a valid URL."
|
| 936 |
+
# Relative URLS not allowed by default
|
| 937 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 938 |
+
field.deserialize("/foo/bar")
|
| 939 |
+
assert excinfo.value.args[0][0] == "Not a valid URL."
|
| 940 |
+
|
| 941 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/1400
|
| 942 |
+
def test_url_field_non_list_validators(self):
|
| 943 |
+
field = fields.Url(validate=(validate.Length(min=16),))
|
| 944 |
+
with pytest.raises(ValidationError, match="Shorter than minimum length"):
|
| 945 |
+
field.deserialize("https://abc.def")
|
| 946 |
+
|
| 947 |
+
def test_relative_url_field_deserialization(self):
|
| 948 |
+
field = fields.Url(relative=True)
|
| 949 |
+
assert field.deserialize("/foo/bar") == "/foo/bar"
|
| 950 |
+
|
| 951 |
+
def test_url_field_schemes_argument(self):
|
| 952 |
+
field = fields.URL()
|
| 953 |
+
url = "ws://test.test"
|
| 954 |
+
with pytest.raises(ValidationError):
|
| 955 |
+
field.deserialize(url)
|
| 956 |
+
field2 = fields.URL(schemes={"http", "https", "ws"})
|
| 957 |
+
assert field2.deserialize(url) == url
|
| 958 |
+
|
| 959 |
+
def test_email_field_deserialization(self):
|
| 960 |
+
field = fields.Email()
|
| 961 |
+
assert field.deserialize("foo@bar.com") == "foo@bar.com"
|
| 962 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 963 |
+
field.deserialize("invalidemail")
|
| 964 |
+
assert excinfo.value.args[0][0] == "Not a valid email address."
|
| 965 |
+
|
| 966 |
+
field = fields.Email(validate=[validate.Length(min=12)])
|
| 967 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 968 |
+
field.deserialize("foo@bar.com")
|
| 969 |
+
assert excinfo.value.args[0][0] == "Shorter than minimum length 12."
|
| 970 |
+
|
| 971 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/1400
|
| 972 |
+
def test_email_field_non_list_validators(self):
|
| 973 |
+
field = fields.Email(validate=(validate.Length(min=9),))
|
| 974 |
+
with pytest.raises(ValidationError, match="Shorter than minimum length"):
|
| 975 |
+
field.deserialize("a@bc.com")
|
| 976 |
+
|
| 977 |
+
def test_function_field_deserialization_is_noop_by_default(self):
|
| 978 |
+
field = fields.Function(lambda x: None)
|
| 979 |
+
# Default is noop
|
| 980 |
+
assert field.deserialize("foo") == "foo"
|
| 981 |
+
assert field.deserialize(42) == 42
|
| 982 |
+
|
| 983 |
+
def test_function_field_deserialization_with_callable(self):
|
| 984 |
+
field = fields.Function(lambda x: None, deserialize=lambda val: val.upper())
|
| 985 |
+
assert field.deserialize("foo") == "FOO"
|
| 986 |
+
|
| 987 |
+
def test_function_field_deserialization_with_context(self):
|
| 988 |
+
class Parent(Schema):
|
| 989 |
+
pass
|
| 990 |
+
|
| 991 |
+
field = fields.Function(
|
| 992 |
+
lambda x: None,
|
| 993 |
+
deserialize=lambda val, context: val.upper() + context["key"],
|
| 994 |
+
)
|
| 995 |
+
field.parent = Parent(context={"key": "BAR"})
|
| 996 |
+
assert field.deserialize("foo") == "FOOBAR"
|
| 997 |
+
|
| 998 |
+
def test_function_field_passed_deserialize_only_is_load_only(self):
|
| 999 |
+
field = fields.Function(deserialize=lambda val: val.upper())
|
| 1000 |
+
assert field.load_only is True
|
| 1001 |
+
|
| 1002 |
+
def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self):
|
| 1003 |
+
field = fields.Function(
|
| 1004 |
+
serialize=lambda val: val.lower(), deserialize=lambda val: val.upper()
|
| 1005 |
+
)
|
| 1006 |
+
assert field.load_only is False
|
| 1007 |
+
|
| 1008 |
+
def test_uuid_field_deserialization(self):
|
| 1009 |
+
field = fields.UUID()
|
| 1010 |
+
uuid_str = str(uuid.uuid4())
|
| 1011 |
+
result = field.deserialize(uuid_str)
|
| 1012 |
+
assert isinstance(result, uuid.UUID)
|
| 1013 |
+
assert str(result) == uuid_str
|
| 1014 |
+
|
| 1015 |
+
uuid4 = uuid.uuid4()
|
| 1016 |
+
result = field.deserialize(uuid4)
|
| 1017 |
+
assert isinstance(result, uuid.UUID)
|
| 1018 |
+
assert result == uuid4
|
| 1019 |
+
|
| 1020 |
+
uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf"
|
| 1021 |
+
result = field.deserialize(uuid_bytes)
|
| 1022 |
+
assert isinstance(result, uuid.UUID)
|
| 1023 |
+
assert result.bytes == uuid_bytes
|
| 1024 |
+
|
| 1025 |
+
@pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"])
|
| 1026 |
+
def test_invalid_uuid_deserialization(self, in_value):
|
| 1027 |
+
field = fields.UUID()
|
| 1028 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1029 |
+
field.deserialize(in_value)
|
| 1030 |
+
|
| 1031 |
+
assert excinfo.value.args[0] == "Not a valid UUID."
|
| 1032 |
+
|
| 1033 |
+
def test_ip_field_deserialization(self):
|
| 1034 |
+
field = fields.IP()
|
| 1035 |
+
ipv4_str = "140.82.118.3"
|
| 1036 |
+
result = field.deserialize(ipv4_str)
|
| 1037 |
+
assert isinstance(result, ipaddress.IPv4Address)
|
| 1038 |
+
assert str(result) == ipv4_str
|
| 1039 |
+
|
| 1040 |
+
ipv6_str = "2a00:1450:4001:824::200e"
|
| 1041 |
+
result = field.deserialize(ipv6_str)
|
| 1042 |
+
assert isinstance(result, ipaddress.IPv6Address)
|
| 1043 |
+
assert str(result) == ipv6_str
|
| 1044 |
+
|
| 1045 |
+
@pytest.mark.parametrize(
|
| 1046 |
+
"in_value",
|
| 1047 |
+
["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"],
|
| 1048 |
+
)
|
| 1049 |
+
def test_invalid_ip_deserialization(self, in_value):
|
| 1050 |
+
field = fields.IP()
|
| 1051 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1052 |
+
field.deserialize(in_value)
|
| 1053 |
+
|
| 1054 |
+
assert excinfo.value.args[0] == "Not a valid IP address."
|
| 1055 |
+
|
| 1056 |
+
def test_ipv4_field_deserialization(self):
|
| 1057 |
+
field = fields.IPv4()
|
| 1058 |
+
ipv4_str = "140.82.118.3"
|
| 1059 |
+
result = field.deserialize(ipv4_str)
|
| 1060 |
+
assert isinstance(result, ipaddress.IPv4Address)
|
| 1061 |
+
assert str(result) == ipv4_str
|
| 1062 |
+
|
| 1063 |
+
@pytest.mark.parametrize(
|
| 1064 |
+
"in_value",
|
| 1065 |
+
[
|
| 1066 |
+
"malformed",
|
| 1067 |
+
123,
|
| 1068 |
+
b"\x01\x02\03",
|
| 1069 |
+
"192.168",
|
| 1070 |
+
"192.168.0.1/24",
|
| 1071 |
+
"2a00:1450:4001:81d::200e",
|
| 1072 |
+
],
|
| 1073 |
+
)
|
| 1074 |
+
def test_invalid_ipv4_deserialization(self, in_value):
|
| 1075 |
+
field = fields.IPv4()
|
| 1076 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1077 |
+
field.deserialize(in_value)
|
| 1078 |
+
|
| 1079 |
+
assert excinfo.value.args[0] == "Not a valid IPv4 address."
|
| 1080 |
+
|
| 1081 |
+
def test_ipv6_field_deserialization(self):
|
| 1082 |
+
field = fields.IPv6()
|
| 1083 |
+
ipv6_str = "2a00:1450:4001:824::200e"
|
| 1084 |
+
result = field.deserialize(ipv6_str)
|
| 1085 |
+
assert isinstance(result, ipaddress.IPv6Address)
|
| 1086 |
+
assert str(result) == ipv6_str
|
| 1087 |
+
|
| 1088 |
+
def test_ipinterface_field_deserialization(self):
|
| 1089 |
+
field = fields.IPInterface()
|
| 1090 |
+
ipv4interface_str = "140.82.118.3/24"
|
| 1091 |
+
result = field.deserialize(ipv4interface_str)
|
| 1092 |
+
assert isinstance(result, ipaddress.IPv4Interface)
|
| 1093 |
+
assert str(result) == ipv4interface_str
|
| 1094 |
+
|
| 1095 |
+
ipv6interface_str = "2a00:1450:4001:824::200e/128"
|
| 1096 |
+
result = field.deserialize(ipv6interface_str)
|
| 1097 |
+
assert isinstance(result, ipaddress.IPv6Interface)
|
| 1098 |
+
assert str(result) == ipv6interface_str
|
| 1099 |
+
|
| 1100 |
+
@pytest.mark.parametrize(
|
| 1101 |
+
"in_value",
|
| 1102 |
+
[
|
| 1103 |
+
"malformed",
|
| 1104 |
+
123,
|
| 1105 |
+
b"\x01\x02\03",
|
| 1106 |
+
"192.168",
|
| 1107 |
+
"192.168.0.1/33",
|
| 1108 |
+
"ff::aa:1::2",
|
| 1109 |
+
"2a00:1450:4001:824::200e/129",
|
| 1110 |
+
],
|
| 1111 |
+
)
|
| 1112 |
+
def test_invalid_ipinterface_deserialization(self, in_value):
|
| 1113 |
+
field = fields.IPInterface()
|
| 1114 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1115 |
+
field.deserialize(in_value)
|
| 1116 |
+
|
| 1117 |
+
assert excinfo.value.args[0] == "Not a valid IP interface."
|
| 1118 |
+
|
| 1119 |
+
def test_ipv4interface_field_deserialization(self):
|
| 1120 |
+
field = fields.IPv4Interface()
|
| 1121 |
+
ipv4interface_str = "140.82.118.3/24"
|
| 1122 |
+
result = field.deserialize(ipv4interface_str)
|
| 1123 |
+
assert isinstance(result, ipaddress.IPv4Interface)
|
| 1124 |
+
assert str(result) == ipv4interface_str
|
| 1125 |
+
|
| 1126 |
+
@pytest.mark.parametrize(
|
| 1127 |
+
"in_value",
|
| 1128 |
+
[
|
| 1129 |
+
"malformed",
|
| 1130 |
+
123,
|
| 1131 |
+
b"\x01\x02\03",
|
| 1132 |
+
"192.168",
|
| 1133 |
+
"192.168.0.1/33",
|
| 1134 |
+
"2a00:1450:4001:81d::200e",
|
| 1135 |
+
"2a00:1450:4001:824::200e/129",
|
| 1136 |
+
],
|
| 1137 |
+
)
|
| 1138 |
+
def test_invalid_ipv4interface_deserialization(self, in_value):
|
| 1139 |
+
field = fields.IPv4Interface()
|
| 1140 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1141 |
+
field.deserialize(in_value)
|
| 1142 |
+
|
| 1143 |
+
assert excinfo.value.args[0] == "Not a valid IPv4 interface."
|
| 1144 |
+
|
| 1145 |
+
def test_ipv6interface_field_deserialization(self):
|
| 1146 |
+
field = fields.IPv6Interface()
|
| 1147 |
+
ipv6interface_str = "2a00:1450:4001:824::200e/128"
|
| 1148 |
+
result = field.deserialize(ipv6interface_str)
|
| 1149 |
+
assert isinstance(result, ipaddress.IPv6Interface)
|
| 1150 |
+
assert str(result) == ipv6interface_str
|
| 1151 |
+
|
| 1152 |
+
@pytest.mark.parametrize(
|
| 1153 |
+
"in_value",
|
| 1154 |
+
[
|
| 1155 |
+
"malformed",
|
| 1156 |
+
123,
|
| 1157 |
+
b"\x01\x02\03",
|
| 1158 |
+
"ff::aa:1::2",
|
| 1159 |
+
"192.168.0.1",
|
| 1160 |
+
"192.168.0.1/24",
|
| 1161 |
+
"2a00:1450:4001:824::200e/129",
|
| 1162 |
+
],
|
| 1163 |
+
)
|
| 1164 |
+
def test_invalid_ipv6interface_deserialization(self, in_value):
|
| 1165 |
+
field = fields.IPv6Interface()
|
| 1166 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1167 |
+
field.deserialize(in_value)
|
| 1168 |
+
|
| 1169 |
+
assert excinfo.value.args[0] == "Not a valid IPv6 interface."
|
| 1170 |
+
|
| 1171 |
+
def test_enum_field_by_symbol_deserialization(self):
|
| 1172 |
+
field = fields.Enum(GenderEnum)
|
| 1173 |
+
assert field.deserialize("male") == GenderEnum.male
|
| 1174 |
+
|
| 1175 |
+
def test_enum_field_by_symbol_invalid_value(self):
|
| 1176 |
+
field = fields.Enum(GenderEnum)
|
| 1177 |
+
with pytest.raises(
|
| 1178 |
+
ValidationError, match="Must be one of: male, female, non_binary."
|
| 1179 |
+
):
|
| 1180 |
+
field.deserialize("dummy")
|
| 1181 |
+
|
| 1182 |
+
def test_enum_field_by_symbol_not_string(self):
|
| 1183 |
+
field = fields.Enum(GenderEnum)
|
| 1184 |
+
with pytest.raises(ValidationError, match="Not a valid string."):
|
| 1185 |
+
field.deserialize(12)
|
| 1186 |
+
|
| 1187 |
+
def test_enum_field_by_value_true_deserialization(self):
|
| 1188 |
+
field = fields.Enum(HairColorEnum, by_value=True)
|
| 1189 |
+
assert field.deserialize("black hair") == HairColorEnum.black
|
| 1190 |
+
field = fields.Enum(GenderEnum, by_value=True)
|
| 1191 |
+
assert field.deserialize(1) == GenderEnum.male
|
| 1192 |
+
|
| 1193 |
+
def test_enum_field_by_value_field_deserialization(self):
|
| 1194 |
+
field = fields.Enum(HairColorEnum, by_value=fields.String)
|
| 1195 |
+
assert field.deserialize("black hair") == HairColorEnum.black
|
| 1196 |
+
field = fields.Enum(GenderEnum, by_value=fields.Integer)
|
| 1197 |
+
assert field.deserialize(1) == GenderEnum.male
|
| 1198 |
+
field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y"))
|
| 1199 |
+
assert field.deserialize("29/02/2004") == DateEnum.date_1
|
| 1200 |
+
|
| 1201 |
+
def test_enum_field_by_value_true_invalid_value(self):
|
| 1202 |
+
field = fields.Enum(HairColorEnum, by_value=True)
|
| 1203 |
+
with pytest.raises(
|
| 1204 |
+
ValidationError,
|
| 1205 |
+
match="Must be one of: black hair, brown hair, blond hair, red hair.",
|
| 1206 |
+
):
|
| 1207 |
+
field.deserialize("dummy")
|
| 1208 |
+
field = fields.Enum(GenderEnum, by_value=True)
|
| 1209 |
+
with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."):
|
| 1210 |
+
field.deserialize(12)
|
| 1211 |
+
|
| 1212 |
+
def test_enum_field_by_value_field_invalid_value(self):
|
| 1213 |
+
field = fields.Enum(HairColorEnum, by_value=fields.String)
|
| 1214 |
+
with pytest.raises(
|
| 1215 |
+
ValidationError,
|
| 1216 |
+
match="Must be one of: black hair, brown hair, blond hair, red hair.",
|
| 1217 |
+
):
|
| 1218 |
+
field.deserialize("dummy")
|
| 1219 |
+
field = fields.Enum(GenderEnum, by_value=fields.Integer)
|
| 1220 |
+
with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."):
|
| 1221 |
+
field.deserialize(12)
|
| 1222 |
+
field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y"))
|
| 1223 |
+
with pytest.raises(
|
| 1224 |
+
ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012."
|
| 1225 |
+
):
|
| 1226 |
+
field.deserialize("28/02/2004")
|
| 1227 |
+
|
| 1228 |
+
def test_enum_field_by_value_true_wrong_type(self):
|
| 1229 |
+
field = fields.Enum(HairColorEnum, by_value=True)
|
| 1230 |
+
with pytest.raises(
|
| 1231 |
+
ValidationError,
|
| 1232 |
+
match="Must be one of: black hair, brown hair, blond hair, red hair.",
|
| 1233 |
+
):
|
| 1234 |
+
field.deserialize("dummy")
|
| 1235 |
+
field = fields.Enum(GenderEnum, by_value=True)
|
| 1236 |
+
with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."):
|
| 1237 |
+
field.deserialize(12)
|
| 1238 |
+
|
| 1239 |
+
def test_enum_field_by_value_field_wrong_type(self):
|
| 1240 |
+
field = fields.Enum(HairColorEnum, by_value=fields.String)
|
| 1241 |
+
with pytest.raises(ValidationError, match="Not a valid string."):
|
| 1242 |
+
field.deserialize(12)
|
| 1243 |
+
field = fields.Enum(GenderEnum, by_value=fields.Integer)
|
| 1244 |
+
with pytest.raises(ValidationError, match="Not a valid integer."):
|
| 1245 |
+
field.deserialize("dummy")
|
| 1246 |
+
field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y"))
|
| 1247 |
+
with pytest.raises(ValidationError, match="Not a valid date."):
|
| 1248 |
+
field.deserialize("30/02/2004")
|
| 1249 |
+
|
| 1250 |
+
def test_deserialization_function_must_be_callable(self):
|
| 1251 |
+
with pytest.raises(TypeError):
|
| 1252 |
+
fields.Function(lambda x: None, deserialize="notvalid")
|
| 1253 |
+
|
| 1254 |
+
def test_method_field_deserialization_is_noop_by_default(self):
|
| 1255 |
+
class MiniUserSchema(Schema):
|
| 1256 |
+
uppername = fields.Method("uppercase_name")
|
| 1257 |
+
|
| 1258 |
+
def uppercase_name(self, obj):
|
| 1259 |
+
return obj.upper()
|
| 1260 |
+
|
| 1261 |
+
s = MiniUserSchema()
|
| 1262 |
+
assert s.fields["uppername"].deserialize("steve") == "steve"
|
| 1263 |
+
|
| 1264 |
+
def test_deserialization_method(self):
|
| 1265 |
+
class MiniUserSchema(Schema):
|
| 1266 |
+
uppername = fields.Method("uppercase_name", deserialize="lowercase_name")
|
| 1267 |
+
|
| 1268 |
+
def uppercase_name(self, obj):
|
| 1269 |
+
return obj.name.upper()
|
| 1270 |
+
|
| 1271 |
+
def lowercase_name(self, value):
|
| 1272 |
+
return value.lower()
|
| 1273 |
+
|
| 1274 |
+
s = MiniUserSchema()
|
| 1275 |
+
assert s.fields["uppername"].deserialize("STEVE") == "steve"
|
| 1276 |
+
|
| 1277 |
+
def test_deserialization_method_must_be_a_method(self):
|
| 1278 |
+
class BadSchema(Schema):
|
| 1279 |
+
uppername = fields.Method("uppercase_name", deserialize="lowercase_name")
|
| 1280 |
+
|
| 1281 |
+
with pytest.raises(AttributeError):
|
| 1282 |
+
BadSchema()
|
| 1283 |
+
|
| 1284 |
+
def test_method_field_deserialize_only(self):
|
| 1285 |
+
class MethodDeserializeOnly(Schema):
|
| 1286 |
+
name = fields.Method(deserialize="lowercase_name")
|
| 1287 |
+
|
| 1288 |
+
def lowercase_name(self, value):
|
| 1289 |
+
return value.lower()
|
| 1290 |
+
|
| 1291 |
+
assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec"
|
| 1292 |
+
|
| 1293 |
+
def test_datetime_list_field_deserialization(self):
|
| 1294 |
+
dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc)
|
| 1295 |
+
dstrings = [each.isoformat() for each in dtimes]
|
| 1296 |
+
field = fields.List(fields.DateTime())
|
| 1297 |
+
result = field.deserialize(dstrings)
|
| 1298 |
+
assert all(isinstance(each, dt.datetime) for each in result)
|
| 1299 |
+
for actual, expected in zip(result, dtimes):
|
| 1300 |
+
assert_date_equal(actual, expected)
|
| 1301 |
+
|
| 1302 |
+
def test_list_field_deserialize_invalid_item(self):
|
| 1303 |
+
field = fields.List(fields.DateTime)
|
| 1304 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1305 |
+
field.deserialize(["badvalue"])
|
| 1306 |
+
assert excinfo.value.args[0] == {0: ["Not a valid datetime."]}
|
| 1307 |
+
|
| 1308 |
+
field = fields.List(fields.Str())
|
| 1309 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1310 |
+
field.deserialize(["good", 42])
|
| 1311 |
+
assert excinfo.value.args[0] == {1: ["Not a valid string."]}
|
| 1312 |
+
|
| 1313 |
+
def test_list_field_deserialize_multiple_invalid_items(self):
|
| 1314 |
+
field = fields.List(
|
| 1315 |
+
fields.Int(
|
| 1316 |
+
validate=validate.Range(10, 20, error="Value {input} not in range")
|
| 1317 |
+
)
|
| 1318 |
+
)
|
| 1319 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1320 |
+
field.deserialize([10, 5, 25])
|
| 1321 |
+
assert len(excinfo.value.args[0]) == 2
|
| 1322 |
+
assert excinfo.value.args[0][1] == ["Value 5 not in range"]
|
| 1323 |
+
assert excinfo.value.args[0][2] == ["Value 25 not in range"]
|
| 1324 |
+
|
| 1325 |
+
@pytest.mark.parametrize("value", ["notalist", 42, {}])
|
| 1326 |
+
def test_list_field_deserialize_value_that_is_not_a_list(self, value):
|
| 1327 |
+
field = fields.List(fields.Str())
|
| 1328 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1329 |
+
field.deserialize(value)
|
| 1330 |
+
assert excinfo.value.args[0] == "Not a valid list."
|
| 1331 |
+
|
| 1332 |
+
def test_datetime_int_tuple_field_deserialization(self):
|
| 1333 |
+
dtime = dt.datetime.now()
|
| 1334 |
+
data = dtime.isoformat(), 42
|
| 1335 |
+
field = fields.Tuple([fields.DateTime(), fields.Integer()])
|
| 1336 |
+
result = field.deserialize(data)
|
| 1337 |
+
|
| 1338 |
+
assert isinstance(result, tuple)
|
| 1339 |
+
assert len(result) == 2
|
| 1340 |
+
for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)):
|
| 1341 |
+
assert isinstance(val, type_)
|
| 1342 |
+
assert val == true_val
|
| 1343 |
+
|
| 1344 |
+
def test_tuple_field_deserialize_invalid_item(self):
|
| 1345 |
+
field = fields.Tuple([fields.DateTime])
|
| 1346 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1347 |
+
field.deserialize(["badvalue"])
|
| 1348 |
+
assert excinfo.value.args[0] == {0: ["Not a valid datetime."]}
|
| 1349 |
+
|
| 1350 |
+
field = fields.Tuple([fields.Str(), fields.Integer()])
|
| 1351 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1352 |
+
field.deserialize(["good", "bad"])
|
| 1353 |
+
assert excinfo.value.args[0] == {1: ["Not a valid integer."]}
|
| 1354 |
+
|
| 1355 |
+
def test_tuple_field_deserialize_multiple_invalid_items(self):
|
| 1356 |
+
validator = validate.Range(10, 20, error="Value {input} not in range")
|
| 1357 |
+
field = fields.Tuple(
|
| 1358 |
+
[
|
| 1359 |
+
fields.Int(validate=validator),
|
| 1360 |
+
fields.Int(validate=validator),
|
| 1361 |
+
fields.Int(validate=validator),
|
| 1362 |
+
]
|
| 1363 |
+
)
|
| 1364 |
+
|
| 1365 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1366 |
+
field.deserialize([10, 5, 25])
|
| 1367 |
+
assert len(excinfo.value.args[0]) == 2
|
| 1368 |
+
assert excinfo.value.args[0][1] == ["Value 5 not in range"]
|
| 1369 |
+
assert excinfo.value.args[0][2] == ["Value 25 not in range"]
|
| 1370 |
+
|
| 1371 |
+
@pytest.mark.parametrize("value", ["notalist", 42, {}])
|
| 1372 |
+
def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value):
|
| 1373 |
+
field = fields.Tuple([fields.Str()])
|
| 1374 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1375 |
+
field.deserialize(value)
|
| 1376 |
+
assert excinfo.value.args[0] == "Not a valid tuple."
|
| 1377 |
+
|
| 1378 |
+
def test_tuple_field_deserialize_invalid_length(self):
|
| 1379 |
+
field = fields.Tuple([fields.Str(), fields.Str()])
|
| 1380 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1381 |
+
field.deserialize([42])
|
| 1382 |
+
assert excinfo.value.args[0] == "Length must be 2."
|
| 1383 |
+
|
| 1384 |
+
def test_constant_field_deserialization(self):
|
| 1385 |
+
field = fields.Constant("something")
|
| 1386 |
+
assert field.deserialize("whatever") == "something"
|
| 1387 |
+
|
| 1388 |
+
def test_constant_is_always_included_in_deserialized_data(self):
|
| 1389 |
+
class MySchema(Schema):
|
| 1390 |
+
foo = fields.Constant(42)
|
| 1391 |
+
|
| 1392 |
+
sch = MySchema()
|
| 1393 |
+
assert sch.load({})["foo"] == 42
|
| 1394 |
+
assert sch.load({"foo": 24})["foo"] == 42
|
| 1395 |
+
|
| 1396 |
+
def test_field_deserialization_with_user_validator_function(self):
|
| 1397 |
+
field = fields.String(validate=lambda s: s.lower() == "valid")
|
| 1398 |
+
assert field.deserialize("Valid") == "Valid"
|
| 1399 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1400 |
+
field.deserialize("invalid")
|
| 1401 |
+
assert excinfo.value.args[0][0] == "Invalid value."
|
| 1402 |
+
assert type(excinfo.value) is ValidationError
|
| 1403 |
+
|
| 1404 |
+
def test_field_deserialization_with_user_validator_class_that_returns_bool(self):
|
| 1405 |
+
class MyValidator:
|
| 1406 |
+
def __call__(self, val):
|
| 1407 |
+
if val == "valid":
|
| 1408 |
+
return True
|
| 1409 |
+
return False
|
| 1410 |
+
|
| 1411 |
+
field = fields.Field(validate=MyValidator())
|
| 1412 |
+
assert field.deserialize("valid") == "valid"
|
| 1413 |
+
with pytest.raises(ValidationError, match="Invalid value."):
|
| 1414 |
+
field.deserialize("invalid")
|
| 1415 |
+
|
| 1416 |
+
def test_field_deserialization_with_user_validator_that_raises_error_with_list(
|
| 1417 |
+
self,
|
| 1418 |
+
):
|
| 1419 |
+
def validator(val):
|
| 1420 |
+
raise ValidationError(["err1", "err2"])
|
| 1421 |
+
|
| 1422 |
+
class MySchema(Schema):
|
| 1423 |
+
foo = fields.Field(validate=validator)
|
| 1424 |
+
|
| 1425 |
+
errors = MySchema().validate({"foo": 42})
|
| 1426 |
+
assert errors["foo"] == ["err1", "err2"]
|
| 1427 |
+
|
| 1428 |
+
def test_validator_must_return_false_to_raise_error(self):
|
| 1429 |
+
# validator returns None, so anything validates
|
| 1430 |
+
field = fields.String(validate=lambda s: None)
|
| 1431 |
+
assert field.deserialize("Valid") == "Valid"
|
| 1432 |
+
# validator returns False, so nothing validates
|
| 1433 |
+
field2 = fields.String(validate=lambda s: False)
|
| 1434 |
+
with pytest.raises(ValidationError):
|
| 1435 |
+
field2.deserialize("invalid")
|
| 1436 |
+
|
| 1437 |
+
def test_field_deserialization_with_validator_with_nonascii_input(self):
|
| 1438 |
+
field = fields.String(validate=lambda s: False)
|
| 1439 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1440 |
+
field.deserialize("привет")
|
| 1441 |
+
assert type(excinfo.value) is ValidationError
|
| 1442 |
+
|
| 1443 |
+
def test_field_deserialization_with_user_validators(self):
|
| 1444 |
+
validators_gen = (
|
| 1445 |
+
func
|
| 1446 |
+
for func in (
|
| 1447 |
+
lambda s: s.lower() == "valid",
|
| 1448 |
+
lambda s: s.lower()[::-1] == "dilav",
|
| 1449 |
+
)
|
| 1450 |
+
)
|
| 1451 |
+
|
| 1452 |
+
m_colletion_type = [
|
| 1453 |
+
fields.String(
|
| 1454 |
+
validate=[
|
| 1455 |
+
lambda s: s.lower() == "valid",
|
| 1456 |
+
lambda s: s.lower()[::-1] == "dilav",
|
| 1457 |
+
]
|
| 1458 |
+
),
|
| 1459 |
+
fields.String(
|
| 1460 |
+
validate=(
|
| 1461 |
+
lambda s: s.lower() == "valid",
|
| 1462 |
+
lambda s: s.lower()[::-1] == "dilav",
|
| 1463 |
+
)
|
| 1464 |
+
),
|
| 1465 |
+
fields.String(validate=validators_gen),
|
| 1466 |
+
]
|
| 1467 |
+
|
| 1468 |
+
for field in m_colletion_type:
|
| 1469 |
+
assert field.deserialize("Valid") == "Valid"
|
| 1470 |
+
with pytest.raises(ValidationError, match="Invalid value."):
|
| 1471 |
+
field.deserialize("invalid")
|
| 1472 |
+
|
| 1473 |
+
def test_field_deserialization_with_custom_error_message(self):
|
| 1474 |
+
field = fields.String(
|
| 1475 |
+
validate=lambda s: s.lower() == "valid",
|
| 1476 |
+
error_messages={"validator_failed": "Bad value."},
|
| 1477 |
+
)
|
| 1478 |
+
with pytest.raises(ValidationError, match="Bad value."):
|
| 1479 |
+
field.deserialize("invalid")
|
| 1480 |
+
|
| 1481 |
+
|
| 1482 |
+
# No custom deserialization behavior, so a dict is returned
|
| 1483 |
+
class SimpleUserSchema(Schema):
|
| 1484 |
+
name = fields.String()
|
| 1485 |
+
age = fields.Float()
|
| 1486 |
+
|
| 1487 |
+
|
| 1488 |
+
class Validator(Schema):
|
| 1489 |
+
email = fields.Email()
|
| 1490 |
+
colors = fields.Str(validate=validate.OneOf(["red", "blue"]))
|
| 1491 |
+
age = fields.Integer(validate=lambda n: n > 0)
|
| 1492 |
+
|
| 1493 |
+
|
| 1494 |
+
class Validators(Schema):
|
| 1495 |
+
email = fields.Email()
|
| 1496 |
+
colors = fields.Str(validate=validate.OneOf(["red", "blue"]))
|
| 1497 |
+
age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100])
|
| 1498 |
+
|
| 1499 |
+
|
| 1500 |
+
class TestSchemaDeserialization:
|
| 1501 |
+
def test_deserialize_to_dict(self):
|
| 1502 |
+
user_dict = {"name": "Monty", "age": "42.3"}
|
| 1503 |
+
result = SimpleUserSchema().load(user_dict)
|
| 1504 |
+
assert result["name"] == "Monty"
|
| 1505 |
+
assert math.isclose(result["age"], 42.3)
|
| 1506 |
+
|
| 1507 |
+
def test_deserialize_with_missing_values(self):
|
| 1508 |
+
user_dict = {"name": "Monty"}
|
| 1509 |
+
result = SimpleUserSchema().load(user_dict)
|
| 1510 |
+
# 'age' is not included in result
|
| 1511 |
+
assert result == {"name": "Monty"}
|
| 1512 |
+
|
| 1513 |
+
def test_deserialize_many(self):
|
| 1514 |
+
users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}]
|
| 1515 |
+
result = SimpleUserSchema(many=True).load(users_data)
|
| 1516 |
+
assert isinstance(result, list)
|
| 1517 |
+
user = result[0]
|
| 1518 |
+
assert user["age"] == int(users_data[0]["age"])
|
| 1519 |
+
|
| 1520 |
+
def test_exclude(self):
|
| 1521 |
+
schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE)
|
| 1522 |
+
result = schema.load({"name": "Monty", "age": 42})
|
| 1523 |
+
assert "name" in result
|
| 1524 |
+
assert "age" not in result
|
| 1525 |
+
|
| 1526 |
+
def test_nested_single_deserialization_to_dict(self):
|
| 1527 |
+
class SimpleBlogSerializer(Schema):
|
| 1528 |
+
title = fields.String()
|
| 1529 |
+
author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE)
|
| 1530 |
+
|
| 1531 |
+
blog_dict = {
|
| 1532 |
+
"title": "Gimme Shelter",
|
| 1533 |
+
"author": {"name": "Mick", "age": "914", "email": "mick@stones.com"},
|
| 1534 |
+
}
|
| 1535 |
+
result = SimpleBlogSerializer().load(blog_dict)
|
| 1536 |
+
author = result["author"]
|
| 1537 |
+
assert author["name"] == "Mick"
|
| 1538 |
+
assert author["age"] == 914
|
| 1539 |
+
assert "email" not in author
|
| 1540 |
+
|
| 1541 |
+
def test_nested_list_deserialization_to_dict(self):
|
| 1542 |
+
class SimpleBlogSerializer(Schema):
|
| 1543 |
+
title = fields.String()
|
| 1544 |
+
authors = fields.Nested(SimpleUserSchema, many=True)
|
| 1545 |
+
|
| 1546 |
+
blog_dict = {
|
| 1547 |
+
"title": "Gimme Shelter",
|
| 1548 |
+
"authors": [
|
| 1549 |
+
{"name": "Mick", "age": "914"},
|
| 1550 |
+
{"name": "Keith", "age": "8442"},
|
| 1551 |
+
],
|
| 1552 |
+
}
|
| 1553 |
+
result = SimpleBlogSerializer().load(blog_dict)
|
| 1554 |
+
assert isinstance(result["authors"], list)
|
| 1555 |
+
author = result["authors"][0]
|
| 1556 |
+
assert author["name"] == "Mick"
|
| 1557 |
+
assert author["age"] == 914
|
| 1558 |
+
|
| 1559 |
+
def test_nested_single_none_not_allowed(self):
|
| 1560 |
+
class PetSchema(Schema):
|
| 1561 |
+
name = fields.Str()
|
| 1562 |
+
|
| 1563 |
+
class OwnerSchema(Schema):
|
| 1564 |
+
pet = fields.Nested(PetSchema(), allow_none=False)
|
| 1565 |
+
|
| 1566 |
+
sch = OwnerSchema()
|
| 1567 |
+
errors = sch.validate({"pet": None})
|
| 1568 |
+
assert "pet" in errors
|
| 1569 |
+
assert errors["pet"] == ["Field may not be null."]
|
| 1570 |
+
|
| 1571 |
+
def test_nested_many_non_not_allowed(self):
|
| 1572 |
+
class PetSchema(Schema):
|
| 1573 |
+
name = fields.Str()
|
| 1574 |
+
|
| 1575 |
+
class StoreSchema(Schema):
|
| 1576 |
+
pets = fields.Nested(PetSchema, allow_none=False, many=True)
|
| 1577 |
+
|
| 1578 |
+
sch = StoreSchema()
|
| 1579 |
+
errors = sch.validate({"pets": None})
|
| 1580 |
+
assert "pets" in errors
|
| 1581 |
+
assert errors["pets"] == ["Field may not be null."]
|
| 1582 |
+
|
| 1583 |
+
def test_nested_single_required_missing(self):
|
| 1584 |
+
class PetSchema(Schema):
|
| 1585 |
+
name = fields.Str()
|
| 1586 |
+
|
| 1587 |
+
class OwnerSchema(Schema):
|
| 1588 |
+
pet = fields.Nested(PetSchema(), required=True)
|
| 1589 |
+
|
| 1590 |
+
sch = OwnerSchema()
|
| 1591 |
+
errors = sch.validate({})
|
| 1592 |
+
assert "pet" in errors
|
| 1593 |
+
assert errors["pet"] == ["Missing data for required field."]
|
| 1594 |
+
|
| 1595 |
+
def test_nested_many_required_missing(self):
|
| 1596 |
+
class PetSchema(Schema):
|
| 1597 |
+
name = fields.Str()
|
| 1598 |
+
|
| 1599 |
+
class StoreSchema(Schema):
|
| 1600 |
+
pets = fields.Nested(PetSchema, required=True, many=True)
|
| 1601 |
+
|
| 1602 |
+
sch = StoreSchema()
|
| 1603 |
+
errors = sch.validate({})
|
| 1604 |
+
assert "pets" in errors
|
| 1605 |
+
assert errors["pets"] == ["Missing data for required field."]
|
| 1606 |
+
|
| 1607 |
+
def test_nested_only_basestring(self):
|
| 1608 |
+
class ANestedSchema(Schema):
|
| 1609 |
+
pk = fields.Str()
|
| 1610 |
+
|
| 1611 |
+
class MainSchema(Schema):
|
| 1612 |
+
pk = fields.Str()
|
| 1613 |
+
child = fields.Pluck(ANestedSchema, "pk")
|
| 1614 |
+
|
| 1615 |
+
sch = MainSchema()
|
| 1616 |
+
result = sch.load({"pk": "123", "child": "456"})
|
| 1617 |
+
assert result["child"]["pk"] == "456"
|
| 1618 |
+
|
| 1619 |
+
def test_nested_only_basestring_with_list_data(self):
|
| 1620 |
+
class ANestedSchema(Schema):
|
| 1621 |
+
pk = fields.Str()
|
| 1622 |
+
|
| 1623 |
+
class MainSchema(Schema):
|
| 1624 |
+
pk = fields.Str()
|
| 1625 |
+
children = fields.Pluck(ANestedSchema, "pk", many=True)
|
| 1626 |
+
|
| 1627 |
+
sch = MainSchema()
|
| 1628 |
+
result = sch.load({"pk": "123", "children": ["456", "789"]})
|
| 1629 |
+
assert result["children"][0]["pk"] == "456"
|
| 1630 |
+
assert result["children"][1]["pk"] == "789"
|
| 1631 |
+
|
| 1632 |
+
def test_nested_none_deserialization(self):
|
| 1633 |
+
class SimpleBlogSerializer(Schema):
|
| 1634 |
+
title = fields.String()
|
| 1635 |
+
author = fields.Nested(SimpleUserSchema, allow_none=True)
|
| 1636 |
+
|
| 1637 |
+
blog_dict = {"title": "Gimme Shelter", "author": None}
|
| 1638 |
+
result = SimpleBlogSerializer().load(blog_dict)
|
| 1639 |
+
assert result["author"] is None
|
| 1640 |
+
assert result["title"] == blog_dict["title"]
|
| 1641 |
+
|
| 1642 |
+
def test_deserialize_with_attribute_param(self):
|
| 1643 |
+
class AliasingUserSerializer(Schema):
|
| 1644 |
+
username = fields.Email(attribute="email")
|
| 1645 |
+
years = fields.Integer(attribute="age")
|
| 1646 |
+
|
| 1647 |
+
data = {"username": "foo@bar.com", "years": "42"}
|
| 1648 |
+
result = AliasingUserSerializer().load(data)
|
| 1649 |
+
assert result["email"] == "foo@bar.com"
|
| 1650 |
+
assert result["age"] == 42
|
| 1651 |
+
|
| 1652 |
+
# regression test for https://github.com/marshmallow-code/marshmallow/issues/450
|
| 1653 |
+
def test_deserialize_with_attribute_param_symmetry(self):
|
| 1654 |
+
class MySchema(Schema):
|
| 1655 |
+
foo = fields.Field(attribute="bar.baz")
|
| 1656 |
+
|
| 1657 |
+
schema = MySchema()
|
| 1658 |
+
dump_data = schema.dump({"bar": {"baz": 42}})
|
| 1659 |
+
assert dump_data == {"foo": 42}
|
| 1660 |
+
|
| 1661 |
+
load_data = schema.load({"foo": 42})
|
| 1662 |
+
assert load_data == {"bar": {"baz": 42}}
|
| 1663 |
+
|
| 1664 |
+
def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name(
|
| 1665 |
+
self,
|
| 1666 |
+
):
|
| 1667 |
+
class AliasingUserSerializer(Schema):
|
| 1668 |
+
username = fields.Email(attribute="email")
|
| 1669 |
+
years = fields.Integer(attribute="age")
|
| 1670 |
+
|
| 1671 |
+
data = {"username": "foobar.com", "years": "42"}
|
| 1672 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1673 |
+
AliasingUserSerializer().load(data)
|
| 1674 |
+
errors = excinfo.value.messages
|
| 1675 |
+
assert errors["username"] == ["Not a valid email address."]
|
| 1676 |
+
|
| 1677 |
+
def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name(
|
| 1678 |
+
self,
|
| 1679 |
+
):
|
| 1680 |
+
class AliasingUserSerializer(Schema):
|
| 1681 |
+
name = fields.String(data_key="Name")
|
| 1682 |
+
username = fields.Email(attribute="email", data_key="UserName")
|
| 1683 |
+
years = fields.Integer(attribute="age", data_key="Years")
|
| 1684 |
+
|
| 1685 |
+
data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"}
|
| 1686 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1687 |
+
AliasingUserSerializer().load(data)
|
| 1688 |
+
errors = excinfo.value.messages
|
| 1689 |
+
assert errors["UserName"] == ["Not a valid email address."]
|
| 1690 |
+
assert errors["Years"] == ["Not a valid integer."]
|
| 1691 |
+
|
| 1692 |
+
def test_deserialize_with_data_key_param(self):
|
| 1693 |
+
class AliasingUserSerializer(Schema):
|
| 1694 |
+
name = fields.String(data_key="Name")
|
| 1695 |
+
username = fields.Email(attribute="email", data_key="UserName")
|
| 1696 |
+
years = fields.Integer(data_key="Years")
|
| 1697 |
+
|
| 1698 |
+
data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"}
|
| 1699 |
+
result = AliasingUserSerializer(unknown=EXCLUDE).load(data)
|
| 1700 |
+
assert result["name"] == "Mick"
|
| 1701 |
+
assert result["email"] == "foo@bar.com"
|
| 1702 |
+
assert "years" not in result
|
| 1703 |
+
|
| 1704 |
+
def test_deserialize_with_data_key_as_empty_string(self):
|
| 1705 |
+
class MySchema(Schema):
|
| 1706 |
+
name = fields.Field(data_key="")
|
| 1707 |
+
|
| 1708 |
+
schema = MySchema()
|
| 1709 |
+
assert schema.load({"": "Grace"}) == {"name": "Grace"}
|
| 1710 |
+
|
| 1711 |
+
def test_deserialize_with_dump_only_param(self):
|
| 1712 |
+
class AliasingUserSerializer(Schema):
|
| 1713 |
+
name = fields.String()
|
| 1714 |
+
years = fields.Integer(dump_only=True)
|
| 1715 |
+
size = fields.Integer(dump_only=True, load_only=True)
|
| 1716 |
+
nicknames = fields.List(fields.Str(), dump_only=True)
|
| 1717 |
+
|
| 1718 |
+
data = {
|
| 1719 |
+
"name": "Mick",
|
| 1720 |
+
"years": "42",
|
| 1721 |
+
"size": "12",
|
| 1722 |
+
"nicknames": ["Your Majesty", "Brenda"],
|
| 1723 |
+
}
|
| 1724 |
+
result = AliasingUserSerializer(unknown=EXCLUDE).load(data)
|
| 1725 |
+
assert result["name"] == "Mick"
|
| 1726 |
+
assert "years" not in result
|
| 1727 |
+
assert "size" not in result
|
| 1728 |
+
assert "nicknames" not in result
|
| 1729 |
+
|
| 1730 |
+
def test_deserialize_with_missing_param_value(self):
|
| 1731 |
+
bdate = dt.datetime(2017, 9, 29)
|
| 1732 |
+
|
| 1733 |
+
class AliasingUserSerializer(Schema):
|
| 1734 |
+
name = fields.String()
|
| 1735 |
+
birthdate = fields.DateTime(load_default=bdate)
|
| 1736 |
+
|
| 1737 |
+
data = {"name": "Mick"}
|
| 1738 |
+
result = AliasingUserSerializer().load(data)
|
| 1739 |
+
assert result["name"] == "Mick"
|
| 1740 |
+
assert result["birthdate"] == bdate
|
| 1741 |
+
|
| 1742 |
+
def test_deserialize_with_missing_param_callable(self):
|
| 1743 |
+
bdate = dt.datetime(2017, 9, 29)
|
| 1744 |
+
|
| 1745 |
+
class AliasingUserSerializer(Schema):
|
| 1746 |
+
name = fields.String()
|
| 1747 |
+
birthdate = fields.DateTime(load_default=lambda: bdate)
|
| 1748 |
+
|
| 1749 |
+
data = {"name": "Mick"}
|
| 1750 |
+
result = AliasingUserSerializer().load(data)
|
| 1751 |
+
assert result["name"] == "Mick"
|
| 1752 |
+
assert result["birthdate"] == bdate
|
| 1753 |
+
|
| 1754 |
+
def test_deserialize_with_missing_param_none(self):
|
| 1755 |
+
class AliasingUserSerializer(Schema):
|
| 1756 |
+
name = fields.String()
|
| 1757 |
+
years = fields.Integer(load_default=None, allow_none=True)
|
| 1758 |
+
|
| 1759 |
+
data = {"name": "Mick"}
|
| 1760 |
+
result = AliasingUserSerializer().load(data)
|
| 1761 |
+
assert result["name"] == "Mick"
|
| 1762 |
+
assert result["years"] is None
|
| 1763 |
+
|
| 1764 |
+
def test_deserialization_raises_with_errors(self):
|
| 1765 |
+
bad_data = {"email": "invalid-email", "colors": "burger", "age": -1}
|
| 1766 |
+
v = Validator()
|
| 1767 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1768 |
+
v.load(bad_data)
|
| 1769 |
+
errors = excinfo.value.messages
|
| 1770 |
+
assert "email" in errors
|
| 1771 |
+
assert "colors" in errors
|
| 1772 |
+
assert "age" in errors
|
| 1773 |
+
|
| 1774 |
+
def test_deserialization_raises_with_errors_with_multiple_validators(self):
|
| 1775 |
+
bad_data = {"email": "invalid-email", "colors": "burger", "age": -1}
|
| 1776 |
+
v = Validators()
|
| 1777 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1778 |
+
v.load(bad_data)
|
| 1779 |
+
errors = excinfo.value.messages
|
| 1780 |
+
assert "email" in errors
|
| 1781 |
+
assert "colors" in errors
|
| 1782 |
+
assert "age" in errors
|
| 1783 |
+
|
| 1784 |
+
def test_deserialization_many_raises_errors(self):
|
| 1785 |
+
bad_data = [
|
| 1786 |
+
{"email": "foo@bar.com", "colors": "red", "age": 18},
|
| 1787 |
+
{"email": "bad", "colors": "pizza", "age": -1},
|
| 1788 |
+
]
|
| 1789 |
+
v = Validator(many=True)
|
| 1790 |
+
with pytest.raises(ValidationError):
|
| 1791 |
+
v.load(bad_data)
|
| 1792 |
+
|
| 1793 |
+
def test_validation_errors_are_stored(self):
|
| 1794 |
+
def validate_field(val):
|
| 1795 |
+
raise ValidationError("Something went wrong")
|
| 1796 |
+
|
| 1797 |
+
class MySchema(Schema):
|
| 1798 |
+
foo = fields.Field(validate=validate_field)
|
| 1799 |
+
|
| 1800 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1801 |
+
MySchema().load({"foo": 42})
|
| 1802 |
+
errors = excinfo.value.messages
|
| 1803 |
+
assert "Something went wrong" in errors["foo"]
|
| 1804 |
+
|
| 1805 |
+
def test_multiple_errors_can_be_stored_for_a_field(self):
|
| 1806 |
+
def validate_with_bool(n):
|
| 1807 |
+
return False
|
| 1808 |
+
|
| 1809 |
+
def validate_with_error(n):
|
| 1810 |
+
raise ValidationError("foo is not valid")
|
| 1811 |
+
|
| 1812 |
+
class MySchema(Schema):
|
| 1813 |
+
foo = fields.Field(
|
| 1814 |
+
required=True, validate=[validate_with_bool, validate_with_error]
|
| 1815 |
+
)
|
| 1816 |
+
|
| 1817 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1818 |
+
MySchema().load({"foo": "bar"})
|
| 1819 |
+
errors = excinfo.value.messages
|
| 1820 |
+
|
| 1821 |
+
assert type(errors["foo"]) is list
|
| 1822 |
+
assert len(errors["foo"]) == 2
|
| 1823 |
+
|
| 1824 |
+
def test_multiple_errors_can_be_stored_for_an_email_field(self):
|
| 1825 |
+
def validate_with_bool(val):
|
| 1826 |
+
return False
|
| 1827 |
+
|
| 1828 |
+
class MySchema(Schema):
|
| 1829 |
+
email = fields.Email(validate=[validate_with_bool])
|
| 1830 |
+
|
| 1831 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1832 |
+
MySchema().load({"email": "foo"})
|
| 1833 |
+
errors = excinfo.value.messages
|
| 1834 |
+
assert len(errors["email"]) == 2
|
| 1835 |
+
assert "Not a valid email address." in errors["email"][0]
|
| 1836 |
+
|
| 1837 |
+
def test_multiple_errors_can_be_stored_for_a_url_field(self):
|
| 1838 |
+
def validate_with_bool(val):
|
| 1839 |
+
return False
|
| 1840 |
+
|
| 1841 |
+
class MySchema(Schema):
|
| 1842 |
+
url = fields.Url(validate=[validate_with_bool])
|
| 1843 |
+
|
| 1844 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1845 |
+
MySchema().load({"url": "foo"})
|
| 1846 |
+
errors = excinfo.value.messages
|
| 1847 |
+
assert len(errors["url"]) == 2
|
| 1848 |
+
assert "Not a valid URL." in errors["url"][0]
|
| 1849 |
+
|
| 1850 |
+
def test_required_value_only_passed_to_validators_if_provided(self):
|
| 1851 |
+
class MySchema(Schema):
|
| 1852 |
+
foo = fields.Field(required=True, validate=lambda f: False)
|
| 1853 |
+
|
| 1854 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1855 |
+
MySchema().load({})
|
| 1856 |
+
errors = excinfo.value.messages
|
| 1857 |
+
# required value missing
|
| 1858 |
+
assert len(errors["foo"]) == 1
|
| 1859 |
+
assert "Missing data for required field." in errors["foo"]
|
| 1860 |
+
|
| 1861 |
+
@pytest.mark.parametrize("partial_schema", [True, False])
|
| 1862 |
+
def test_partial_deserialization(self, partial_schema):
|
| 1863 |
+
class MySchema(Schema):
|
| 1864 |
+
foo = fields.Field(required=True)
|
| 1865 |
+
bar = fields.Field(required=True)
|
| 1866 |
+
|
| 1867 |
+
schema_args = {}
|
| 1868 |
+
load_args = {}
|
| 1869 |
+
if partial_schema:
|
| 1870 |
+
schema_args["partial"] = True
|
| 1871 |
+
else:
|
| 1872 |
+
load_args["partial"] = True
|
| 1873 |
+
data = MySchema(**schema_args).load({"foo": 3}, **load_args)
|
| 1874 |
+
|
| 1875 |
+
assert data["foo"] == 3
|
| 1876 |
+
assert "bar" not in data
|
| 1877 |
+
|
| 1878 |
+
def test_partial_fields_deserialization(self):
|
| 1879 |
+
class MySchema(Schema):
|
| 1880 |
+
foo = fields.Field(required=True)
|
| 1881 |
+
bar = fields.Field(required=True)
|
| 1882 |
+
baz = fields.Field(required=True)
|
| 1883 |
+
|
| 1884 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1885 |
+
MySchema().load({"foo": 3}, partial=tuple())
|
| 1886 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 1887 |
+
assert data["foo"] == 3
|
| 1888 |
+
assert "bar" in errors
|
| 1889 |
+
assert "baz" in errors
|
| 1890 |
+
|
| 1891 |
+
data = MySchema().load({"foo": 3}, partial=("bar", "baz"))
|
| 1892 |
+
assert data["foo"] == 3
|
| 1893 |
+
assert "bar" not in data
|
| 1894 |
+
assert "baz" not in data
|
| 1895 |
+
|
| 1896 |
+
data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz"))
|
| 1897 |
+
assert data["foo"] == 3
|
| 1898 |
+
assert "bar" not in data
|
| 1899 |
+
assert "baz" not in data
|
| 1900 |
+
|
| 1901 |
+
def test_partial_fields_validation(self):
|
| 1902 |
+
class MySchema(Schema):
|
| 1903 |
+
foo = fields.Field(required=True)
|
| 1904 |
+
bar = fields.Field(required=True)
|
| 1905 |
+
baz = fields.Field(required=True)
|
| 1906 |
+
|
| 1907 |
+
errors = MySchema().validate({"foo": 3}, partial=tuple())
|
| 1908 |
+
assert "bar" in errors
|
| 1909 |
+
assert "baz" in errors
|
| 1910 |
+
|
| 1911 |
+
errors = MySchema().validate({"foo": 3}, partial=("bar", "baz"))
|
| 1912 |
+
assert errors == {}
|
| 1913 |
+
|
| 1914 |
+
errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz"))
|
| 1915 |
+
assert errors == {}
|
| 1916 |
+
|
| 1917 |
+
def test_unknown_fields_deserialization(self):
|
| 1918 |
+
class MySchema(Schema):
|
| 1919 |
+
foo = fields.Integer()
|
| 1920 |
+
|
| 1921 |
+
data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5})
|
| 1922 |
+
assert data["foo"] == 3
|
| 1923 |
+
assert "bar" not in data
|
| 1924 |
+
|
| 1925 |
+
data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE)
|
| 1926 |
+
assert data["foo"] == 3
|
| 1927 |
+
assert "bar" not in data
|
| 1928 |
+
|
| 1929 |
+
data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE)
|
| 1930 |
+
assert data["foo"] == 3
|
| 1931 |
+
assert data["bar"]
|
| 1932 |
+
|
| 1933 |
+
data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5})
|
| 1934 |
+
assert data["foo"] == 3
|
| 1935 |
+
assert data["bar"]
|
| 1936 |
+
|
| 1937 |
+
with pytest.raises(ValidationError, match="foo"):
|
| 1938 |
+
MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5})
|
| 1939 |
+
|
| 1940 |
+
data = MySchema(unknown=INCLUDE, many=True).load(
|
| 1941 |
+
[{"foo": 1}, {"foo": 3, "bar": 5}]
|
| 1942 |
+
)
|
| 1943 |
+
assert "foo" in data[1]
|
| 1944 |
+
assert "bar" in data[1]
|
| 1945 |
+
|
| 1946 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1947 |
+
MySchema().load({"foo": 3, "bar": 5})
|
| 1948 |
+
err = excinfo.value
|
| 1949 |
+
assert "bar" in err.messages
|
| 1950 |
+
assert err.messages["bar"] == ["Unknown field."]
|
| 1951 |
+
|
| 1952 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 1953 |
+
MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}])
|
| 1954 |
+
err = excinfo.value
|
| 1955 |
+
assert 0 in err.messages
|
| 1956 |
+
assert "foo" in err.messages[0]
|
| 1957 |
+
assert err.messages[0]["foo"] == ["Not a valid integer."]
|
| 1958 |
+
assert 1 in err.messages
|
| 1959 |
+
assert "bar" in err.messages[1]
|
| 1960 |
+
assert err.messages[1]["bar"] == ["Unknown field."]
|
| 1961 |
+
|
| 1962 |
+
def test_unknown_fields_deserialization_precedence(self):
|
| 1963 |
+
class MySchema(Schema):
|
| 1964 |
+
class Meta:
|
| 1965 |
+
unknown = INCLUDE
|
| 1966 |
+
|
| 1967 |
+
foo = fields.Integer()
|
| 1968 |
+
|
| 1969 |
+
data = MySchema().load({"foo": 3, "bar": 5})
|
| 1970 |
+
assert data["foo"] == 3
|
| 1971 |
+
assert data["bar"] == 5
|
| 1972 |
+
|
| 1973 |
+
data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5})
|
| 1974 |
+
assert data["foo"] == 3
|
| 1975 |
+
assert "bar" not in data
|
| 1976 |
+
|
| 1977 |
+
data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE)
|
| 1978 |
+
assert data["foo"] == 3
|
| 1979 |
+
assert "bar" not in data
|
| 1980 |
+
|
| 1981 |
+
with pytest.raises(ValidationError):
|
| 1982 |
+
MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE)
|
| 1983 |
+
|
| 1984 |
+
def test_unknown_fields_deserialization_with_data_key(self):
|
| 1985 |
+
class MySchema(Schema):
|
| 1986 |
+
foo = fields.Integer(data_key="Foo")
|
| 1987 |
+
|
| 1988 |
+
data = MySchema().load({"Foo": 1})
|
| 1989 |
+
assert data["foo"] == 1
|
| 1990 |
+
assert "Foo" not in data
|
| 1991 |
+
|
| 1992 |
+
data = MySchema(unknown=RAISE).load({"Foo": 1})
|
| 1993 |
+
assert data["foo"] == 1
|
| 1994 |
+
assert "Foo" not in data
|
| 1995 |
+
|
| 1996 |
+
with pytest.raises(ValidationError):
|
| 1997 |
+
MySchema(unknown=RAISE).load({"foo": 1})
|
| 1998 |
+
|
| 1999 |
+
data = MySchema(unknown=INCLUDE).load({"Foo": 1})
|
| 2000 |
+
assert data["foo"] == 1
|
| 2001 |
+
assert "Foo" not in data
|
| 2002 |
+
|
| 2003 |
+
def test_unknown_fields_deserialization_with_index_errors_false(self):
|
| 2004 |
+
class MySchema(Schema):
|
| 2005 |
+
foo = fields.Integer()
|
| 2006 |
+
|
| 2007 |
+
class Meta:
|
| 2008 |
+
unknown = RAISE
|
| 2009 |
+
index_errors = False
|
| 2010 |
+
|
| 2011 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2012 |
+
MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}])
|
| 2013 |
+
err = excinfo.value
|
| 2014 |
+
assert 1 not in err.messages
|
| 2015 |
+
assert "foo" in err.messages
|
| 2016 |
+
assert "bar" in err.messages
|
| 2017 |
+
assert err.messages["foo"] == ["Not a valid integer."]
|
| 2018 |
+
assert err.messages["bar"] == ["Unknown field."]
|
| 2019 |
+
|
| 2020 |
+
def test_dump_only_fields_considered_unknown(self):
|
| 2021 |
+
class MySchema(Schema):
|
| 2022 |
+
foo = fields.Int(dump_only=True)
|
| 2023 |
+
|
| 2024 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2025 |
+
MySchema().load({"foo": 42})
|
| 2026 |
+
err = excinfo.value
|
| 2027 |
+
assert "foo" in err.messages
|
| 2028 |
+
assert err.messages["foo"] == ["Unknown field."]
|
| 2029 |
+
|
| 2030 |
+
# When unknown = INCLUDE, dump-only fields are included as unknown
|
| 2031 |
+
# without any validation.
|
| 2032 |
+
data = MySchema(unknown=INCLUDE).load({"foo": "LOL"})
|
| 2033 |
+
assert data["foo"] == "LOL"
|
| 2034 |
+
|
| 2035 |
+
def test_unknown_fields_do_not_unpack_dotted_names(self):
|
| 2036 |
+
class MySchema(Schema):
|
| 2037 |
+
class Meta:
|
| 2038 |
+
unknown = INCLUDE
|
| 2039 |
+
|
| 2040 |
+
foo = fields.Str()
|
| 2041 |
+
bar = fields.Str(data_key="bar.baz")
|
| 2042 |
+
|
| 2043 |
+
# dotted names are still supported
|
| 2044 |
+
data = MySchema().load({"foo": "hi", "bar.baz": "okay"})
|
| 2045 |
+
assert data == {"foo": "hi", "bar": "okay"}
|
| 2046 |
+
|
| 2047 |
+
# but extra keys included via unknown=INCLUDE are not transformed into nested dicts
|
| 2048 |
+
data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"})
|
| 2049 |
+
assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"}
|
| 2050 |
+
|
| 2051 |
+
|
| 2052 |
+
validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x])
|
| 2053 |
+
|
| 2054 |
+
validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0])
|
| 2055 |
+
|
| 2056 |
+
validators_gen_str = (
|
| 2057 |
+
func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"]
|
| 2058 |
+
)
|
| 2059 |
+
|
| 2060 |
+
|
| 2061 |
+
class TestValidation:
|
| 2062 |
+
def test_integer_with_validator(self):
|
| 2063 |
+
field = fields.Integer(validate=lambda x: 18 <= x <= 24)
|
| 2064 |
+
out = field.deserialize("20")
|
| 2065 |
+
assert out == 20
|
| 2066 |
+
with pytest.raises(ValidationError):
|
| 2067 |
+
field.deserialize(25)
|
| 2068 |
+
|
| 2069 |
+
@pytest.mark.parametrize(
|
| 2070 |
+
"field",
|
| 2071 |
+
[
|
| 2072 |
+
fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]),
|
| 2073 |
+
fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)),
|
| 2074 |
+
fields.Integer(validate=validators_gen),
|
| 2075 |
+
],
|
| 2076 |
+
)
|
| 2077 |
+
def test_integer_with_validators(self, field):
|
| 2078 |
+
out = field.deserialize("20")
|
| 2079 |
+
assert out == 20
|
| 2080 |
+
with pytest.raises(ValidationError):
|
| 2081 |
+
field.deserialize(25)
|
| 2082 |
+
|
| 2083 |
+
@pytest.mark.parametrize(
|
| 2084 |
+
"field",
|
| 2085 |
+
[
|
| 2086 |
+
fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]),
|
| 2087 |
+
fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)),
|
| 2088 |
+
fields.Float(validate=validators_gen_float),
|
| 2089 |
+
],
|
| 2090 |
+
)
|
| 2091 |
+
def test_float_with_validators(self, field):
|
| 2092 |
+
assert field.deserialize(3.14)
|
| 2093 |
+
with pytest.raises(ValidationError):
|
| 2094 |
+
field.deserialize(4.2)
|
| 2095 |
+
|
| 2096 |
+
def test_string_validator(self):
|
| 2097 |
+
field = fields.String(validate=lambda n: len(n) == 3)
|
| 2098 |
+
assert field.deserialize("Joe") == "Joe"
|
| 2099 |
+
with pytest.raises(ValidationError):
|
| 2100 |
+
field.deserialize("joseph")
|
| 2101 |
+
|
| 2102 |
+
def test_function_validator(self):
|
| 2103 |
+
field = fields.Function(
|
| 2104 |
+
lambda d: d.name.upper(), validate=lambda n: len(n) == 3
|
| 2105 |
+
)
|
| 2106 |
+
assert field.deserialize("joe")
|
| 2107 |
+
with pytest.raises(ValidationError):
|
| 2108 |
+
field.deserialize("joseph")
|
| 2109 |
+
|
| 2110 |
+
@pytest.mark.parametrize(
|
| 2111 |
+
"field",
|
| 2112 |
+
[
|
| 2113 |
+
fields.Function(
|
| 2114 |
+
lambda d: d.name.upper(),
|
| 2115 |
+
validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"],
|
| 2116 |
+
),
|
| 2117 |
+
fields.Function(
|
| 2118 |
+
lambda d: d.name.upper(),
|
| 2119 |
+
validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"),
|
| 2120 |
+
),
|
| 2121 |
+
fields.Function(lambda d: d.name.upper(), validate=validators_gen_str),
|
| 2122 |
+
],
|
| 2123 |
+
)
|
| 2124 |
+
def test_function_validators(self, field):
|
| 2125 |
+
assert field.deserialize("joe")
|
| 2126 |
+
with pytest.raises(ValidationError):
|
| 2127 |
+
field.deserialize("joseph")
|
| 2128 |
+
|
| 2129 |
+
def test_method_validator(self):
|
| 2130 |
+
class MethodSerializer(Schema):
|
| 2131 |
+
name = fields.Method(
|
| 2132 |
+
"get_name", deserialize="get_name", validate=lambda n: len(n) == 3
|
| 2133 |
+
)
|
| 2134 |
+
|
| 2135 |
+
def get_name(self, val):
|
| 2136 |
+
return val.upper()
|
| 2137 |
+
|
| 2138 |
+
assert MethodSerializer().load({"name": "joe"})
|
| 2139 |
+
with pytest.raises(ValidationError, match="Invalid value."):
|
| 2140 |
+
MethodSerializer().load({"name": "joseph"})
|
| 2141 |
+
|
| 2142 |
+
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/269
|
| 2143 |
+
def test_nested_data_is_stored_when_validation_fails(self):
|
| 2144 |
+
class SchemaA(Schema):
|
| 2145 |
+
x = fields.Integer()
|
| 2146 |
+
y = fields.Integer(validate=lambda n: n > 0)
|
| 2147 |
+
z = fields.Integer()
|
| 2148 |
+
|
| 2149 |
+
class SchemaB(Schema):
|
| 2150 |
+
w = fields.Integer()
|
| 2151 |
+
n = fields.Nested(SchemaA)
|
| 2152 |
+
|
| 2153 |
+
sch = SchemaB()
|
| 2154 |
+
|
| 2155 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2156 |
+
sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}})
|
| 2157 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 2158 |
+
assert "z" in errors["n"]
|
| 2159 |
+
assert data == {"w": 90, "n": {"x": 90, "y": 89}}
|
| 2160 |
+
|
| 2161 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2162 |
+
sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}})
|
| 2163 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 2164 |
+
assert "y" in errors["n"]
|
| 2165 |
+
assert data == {"w": 90, "n": {"x": 90, "z": 180}}
|
| 2166 |
+
|
| 2167 |
+
def test_false_value_validation(self):
|
| 2168 |
+
class Sch(Schema):
|
| 2169 |
+
lamb = fields.Raw(validate=lambda x: x is False)
|
| 2170 |
+
equal = fields.Raw(validate=Equal(False))
|
| 2171 |
+
|
| 2172 |
+
errors = Sch().validate({"lamb": False, "equal": False})
|
| 2173 |
+
assert not errors
|
| 2174 |
+
errors = Sch().validate({"lamb": True, "equal": True})
|
| 2175 |
+
assert "lamb" in errors
|
| 2176 |
+
assert errors["lamb"] == ["Invalid value."]
|
| 2177 |
+
assert "equal" in errors
|
| 2178 |
+
assert errors["equal"] == ["Must be equal to False."]
|
| 2179 |
+
|
| 2180 |
+
def test_nested_partial_load(self):
|
| 2181 |
+
class SchemaA(Schema):
|
| 2182 |
+
x = fields.Integer(required=True)
|
| 2183 |
+
y = fields.Integer()
|
| 2184 |
+
|
| 2185 |
+
class SchemaB(Schema):
|
| 2186 |
+
z = fields.Nested(SchemaA)
|
| 2187 |
+
|
| 2188 |
+
b_dict = {"z": {"y": 42}}
|
| 2189 |
+
# Partial loading shouldn't generate any errors.
|
| 2190 |
+
result = SchemaB().load(b_dict, partial=True)
|
| 2191 |
+
assert result["z"]["y"] == 42
|
| 2192 |
+
# Non partial loading should complain about missing values.
|
| 2193 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2194 |
+
SchemaB().load(b_dict)
|
| 2195 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 2196 |
+
assert data["z"]["y"] == 42
|
| 2197 |
+
assert "z" in errors
|
| 2198 |
+
assert "x" in errors["z"]
|
| 2199 |
+
|
| 2200 |
+
def test_deeply_nested_partial_load(self):
|
| 2201 |
+
class SchemaC(Schema):
|
| 2202 |
+
x = fields.Integer(required=True)
|
| 2203 |
+
y = fields.Integer()
|
| 2204 |
+
|
| 2205 |
+
class SchemaB(Schema):
|
| 2206 |
+
c = fields.Nested(SchemaC)
|
| 2207 |
+
|
| 2208 |
+
class SchemaA(Schema):
|
| 2209 |
+
b = fields.Nested(SchemaB)
|
| 2210 |
+
|
| 2211 |
+
a_dict = {"b": {"c": {"y": 42}}}
|
| 2212 |
+
# Partial loading shouldn't generate any errors.
|
| 2213 |
+
result = SchemaA().load(a_dict, partial=True)
|
| 2214 |
+
assert result["b"]["c"]["y"] == 42
|
| 2215 |
+
# Non partial loading should complain about missing values.
|
| 2216 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2217 |
+
SchemaA().load(a_dict)
|
| 2218 |
+
data, errors = excinfo.value.valid_data, excinfo.value.messages
|
| 2219 |
+
assert data["b"]["c"]["y"] == 42
|
| 2220 |
+
assert "b" in errors
|
| 2221 |
+
assert "c" in errors["b"]
|
| 2222 |
+
assert "x" in errors["b"]["c"]
|
| 2223 |
+
|
| 2224 |
+
def test_nested_partial_tuple(self):
|
| 2225 |
+
class SchemaA(Schema):
|
| 2226 |
+
x = fields.Integer(required=True)
|
| 2227 |
+
y = fields.Integer(required=True)
|
| 2228 |
+
|
| 2229 |
+
class SchemaB(Schema):
|
| 2230 |
+
z = fields.Nested(SchemaA)
|
| 2231 |
+
|
| 2232 |
+
b_dict = {"z": {"y": 42}}
|
| 2233 |
+
# If we ignore the missing z.x, z.y should still load.
|
| 2234 |
+
result = SchemaB().load(b_dict, partial=("z.x",))
|
| 2235 |
+
assert result["z"]["y"] == 42
|
| 2236 |
+
# If we ignore a missing z.y we should get a validation error.
|
| 2237 |
+
with pytest.raises(ValidationError):
|
| 2238 |
+
SchemaB().load(b_dict, partial=("z.y",))
|
| 2239 |
+
|
| 2240 |
+
def test_nested_partial_default(self):
|
| 2241 |
+
class SchemaA(Schema):
|
| 2242 |
+
x = fields.Integer(required=True)
|
| 2243 |
+
y = fields.Integer(required=True)
|
| 2244 |
+
|
| 2245 |
+
class SchemaB(Schema):
|
| 2246 |
+
z = fields.Nested(SchemaA(partial=("x",)))
|
| 2247 |
+
|
| 2248 |
+
b_dict = {"z": {"y": 42}}
|
| 2249 |
+
# Nested partial args should be respected.
|
| 2250 |
+
result = SchemaB().load(b_dict)
|
| 2251 |
+
assert result["z"]["y"] == 42
|
| 2252 |
+
with pytest.raises(ValidationError):
|
| 2253 |
+
SchemaB().load({"z": {"x": 0}})
|
| 2254 |
+
|
| 2255 |
+
|
| 2256 |
+
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
|
| 2257 |
+
def test_required_field_failure(FieldClass): # noqa
|
| 2258 |
+
class RequireSchema(Schema):
|
| 2259 |
+
age = FieldClass(required=True)
|
| 2260 |
+
|
| 2261 |
+
user_data = {"name": "Phil"}
|
| 2262 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2263 |
+
RequireSchema().load(user_data)
|
| 2264 |
+
errors = excinfo.value.messages
|
| 2265 |
+
assert "Missing data for required field." in errors["age"]
|
| 2266 |
+
|
| 2267 |
+
|
| 2268 |
+
@pytest.mark.parametrize(
|
| 2269 |
+
"message",
|
| 2270 |
+
[
|
| 2271 |
+
"My custom required message",
|
| 2272 |
+
{"error": "something", "code": 400},
|
| 2273 |
+
["first error", "second error"],
|
| 2274 |
+
],
|
| 2275 |
+
)
|
| 2276 |
+
def test_required_message_can_be_changed(message):
|
| 2277 |
+
class RequireSchema(Schema):
|
| 2278 |
+
age = fields.Integer(required=True, error_messages={"required": message})
|
| 2279 |
+
|
| 2280 |
+
user_data = {"name": "Phil"}
|
| 2281 |
+
with pytest.raises(ValidationError) as excinfo:
|
| 2282 |
+
RequireSchema().load(user_data)
|
| 2283 |
+
errors = excinfo.value.messages
|
| 2284 |
+
expected = [message] if isinstance(message, str) else message
|
| 2285 |
+
assert expected == errors["age"]
|
| 2286 |
+
|
| 2287 |
+
|
| 2288 |
+
@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE))
|
| 2289 |
+
@pytest.mark.parametrize("data", [True, False, 42, None, []])
|
| 2290 |
+
def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown):
|
| 2291 |
+
class MySchema(Schema):
|
| 2292 |
+
foo = fields.Field()
|
| 2293 |
+
bar = fields.Field()
|
| 2294 |
+
|
| 2295 |
+
with pytest.raises(ValidationError, match="Invalid input type.") as excinfo:
|
| 2296 |
+
MySchema(unknown=unknown).load(data)
|
| 2297 |
+
exc = excinfo.value
|
| 2298 |
+
assert list(exc.messages.keys()) == ["_schema"]
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_error_store.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import namedtuple
|
| 2 |
+
|
| 3 |
+
from marshmallow import missing
|
| 4 |
+
from marshmallow.error_store import merge_errors
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_missing_is_falsy():
|
| 8 |
+
assert bool(missing) is False
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
CustomError = namedtuple("CustomError", ["code", "message"])
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestMergeErrors:
|
| 15 |
+
def test_merging_none_and_string(self):
|
| 16 |
+
assert "error1" == merge_errors(None, "error1")
|
| 17 |
+
|
| 18 |
+
def test_merging_none_and_custom_error(self):
|
| 19 |
+
assert CustomError(123, "error1") == merge_errors(
|
| 20 |
+
None, CustomError(123, "error1")
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
def test_merging_none_and_list(self):
|
| 24 |
+
assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"])
|
| 25 |
+
|
| 26 |
+
def test_merging_none_and_dict(self):
|
| 27 |
+
assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"})
|
| 28 |
+
|
| 29 |
+
def test_merging_string_and_none(self):
|
| 30 |
+
assert "error1" == merge_errors("error1", None)
|
| 31 |
+
|
| 32 |
+
def test_merging_custom_error_and_none(self):
|
| 33 |
+
assert CustomError(123, "error1") == merge_errors(
|
| 34 |
+
CustomError(123, "error1"), None
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
def test_merging_list_and_none(self):
|
| 38 |
+
assert ["error1", "error2"] == merge_errors(["error1", "error2"], None)
|
| 39 |
+
|
| 40 |
+
def test_merging_dict_and_none(self):
|
| 41 |
+
assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None)
|
| 42 |
+
|
| 43 |
+
def test_merging_string_and_string(self):
|
| 44 |
+
assert ["error1", "error2"] == merge_errors("error1", "error2")
|
| 45 |
+
|
| 46 |
+
def test_merging_custom_error_and_string(self):
|
| 47 |
+
assert [CustomError(123, "error1"), "error2"] == merge_errors(
|
| 48 |
+
CustomError(123, "error1"), "error2"
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def test_merging_string_and_custom_error(self):
|
| 52 |
+
assert ["error1", CustomError(123, "error2")] == merge_errors(
|
| 53 |
+
"error1", CustomError(123, "error2")
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def test_merging_custom_error_and_custom_error(self):
|
| 57 |
+
assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors(
|
| 58 |
+
CustomError(123, "error1"), CustomError(456, "error2")
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def test_merging_string_and_list(self):
|
| 62 |
+
assert ["error1", "error2"] == merge_errors("error1", ["error2"])
|
| 63 |
+
|
| 64 |
+
def test_merging_string_and_dict(self):
|
| 65 |
+
assert {"_schema": "error1", "field1": "error2"} == merge_errors(
|
| 66 |
+
"error1", {"field1": "error2"}
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
def test_merging_string_and_dict_with_schema_error(self):
|
| 70 |
+
assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors(
|
| 71 |
+
"error1", {"_schema": "error2", "field1": "error3"}
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def test_merging_custom_error_and_list(self):
|
| 75 |
+
assert [CustomError(123, "error1"), "error2"] == merge_errors(
|
| 76 |
+
CustomError(123, "error1"), ["error2"]
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
def test_merging_custom_error_and_dict(self):
|
| 80 |
+
assert {
|
| 81 |
+
"_schema": CustomError(123, "error1"),
|
| 82 |
+
"field1": "error2",
|
| 83 |
+
} == merge_errors(CustomError(123, "error1"), {"field1": "error2"})
|
| 84 |
+
|
| 85 |
+
def test_merging_custom_error_and_dict_with_schema_error(self):
|
| 86 |
+
assert {
|
| 87 |
+
"_schema": [CustomError(123, "error1"), "error2"],
|
| 88 |
+
"field1": "error3",
|
| 89 |
+
} == merge_errors(
|
| 90 |
+
CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"}
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def test_merging_list_and_string(self):
|
| 94 |
+
assert ["error1", "error2"] == merge_errors(["error1"], "error2")
|
| 95 |
+
|
| 96 |
+
def test_merging_list_and_custom_error(self):
|
| 97 |
+
assert ["error1", CustomError(123, "error2")] == merge_errors(
|
| 98 |
+
["error1"], CustomError(123, "error2")
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def test_merging_list_and_list(self):
|
| 102 |
+
assert ["error1", "error2"] == merge_errors(["error1"], ["error2"])
|
| 103 |
+
|
| 104 |
+
def test_merging_list_and_dict(self):
|
| 105 |
+
assert {"_schema": ["error1"], "field1": "error2"} == merge_errors(
|
| 106 |
+
["error1"], {"field1": "error2"}
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
def test_merging_list_and_dict_with_schema_error(self):
|
| 110 |
+
assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors(
|
| 111 |
+
["error1"], {"_schema": "error2", "field1": "error3"}
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
def test_merging_dict_and_string(self):
|
| 115 |
+
assert {"_schema": "error2", "field1": "error1"} == merge_errors(
|
| 116 |
+
{"field1": "error1"}, "error2"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
def test_merging_dict_and_custom_error(self):
|
| 120 |
+
assert {
|
| 121 |
+
"_schema": CustomError(123, "error2"),
|
| 122 |
+
"field1": "error1",
|
| 123 |
+
} == merge_errors({"field1": "error1"}, CustomError(123, "error2"))
|
| 124 |
+
|
| 125 |
+
def test_merging_dict_and_list(self):
|
| 126 |
+
assert {"_schema": ["error2"], "field1": "error1"} == merge_errors(
|
| 127 |
+
{"field1": "error1"}, ["error2"]
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
def test_merging_dict_and_dict(self):
|
| 131 |
+
assert {
|
| 132 |
+
"field1": "error1",
|
| 133 |
+
"field2": ["error2", "error3"],
|
| 134 |
+
"field3": "error4",
|
| 135 |
+
} == merge_errors(
|
| 136 |
+
{"field1": "error1", "field2": "error2"},
|
| 137 |
+
{"field2": "error3", "field3": "error4"},
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def test_deep_merging_dicts(self):
|
| 141 |
+
assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors(
|
| 142 |
+
{"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}}
|
| 143 |
+
)
|
tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_exceptions.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from marshmallow.exceptions import ValidationError
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestValidationError:
|
| 7 |
+
def test_stores_message_in_list(self):
|
| 8 |
+
err = ValidationError("foo")
|
| 9 |
+
assert err.messages == ["foo"]
|
| 10 |
+
|
| 11 |
+
def test_can_pass_list_of_messages(self):
|
| 12 |
+
err = ValidationError(["foo", "bar"])
|
| 13 |
+
assert err.messages == ["foo", "bar"]
|
| 14 |
+
|
| 15 |
+
def test_stores_dictionaries(self):
|
| 16 |
+
messages = {"user": {"email": ["email is invalid"]}}
|
| 17 |
+
err = ValidationError(messages)
|
| 18 |
+
assert err.messages == messages
|
| 19 |
+
|
| 20 |
+
def test_can_store_field_name(self):
|
| 21 |
+
err = ValidationError("invalid email", field_name="email")
|
| 22 |
+
assert err.field_name == "email"
|
| 23 |
+
|
| 24 |
+
def test_str(self):
|
| 25 |
+
err = ValidationError("invalid email")
|
| 26 |
+
assert str(err) == "invalid email"
|
| 27 |
+
|
| 28 |
+
err2 = ValidationError("invalid email", "email")
|
| 29 |
+
assert str(err2) == "invalid email"
|
| 30 |
+
|
| 31 |
+
def test_stores_dictionaries_in_messages_dict(self):
|
| 32 |
+
messages = {"user": {"email": ["email is invalid"]}}
|
| 33 |
+
err = ValidationError(messages)
|
| 34 |
+
assert err.messages_dict == messages
|
| 35 |
+
|
| 36 |
+
def test_messages_dict_type_error_on_badval(self):
|
| 37 |
+
err = ValidationError("foo")
|
| 38 |
+
with pytest.raises(TypeError) as excinfo:
|
| 39 |
+
err.messages_dict # noqa: B018
|
| 40 |
+
assert "cannot access 'messages_dict' when 'messages' is of type list" in str(
|
| 41 |
+
excinfo.value
|
| 42 |
+
)
|