1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
|
from unittest import mock
import pytest
from flask import Flask
from marshmallow import Schema
from werkzeug.exceptions import BadRequest, HTTPException
from webargs import ValidationError, fields, missing
from webargs.core import json
from webargs.flaskparser import abort, parser
from webargs.testing import CommonTestCase
from .apps.flask_app import FLASK_SUPPORTS_ASYNC, app
class TestFlaskParser(CommonTestCase):
def create_app(self):
return app
def test_parsing_view_args(self, testapp):
res = testapp.get("/echo_view_arg/42")
assert res.json == {"view_arg": 42}
def test_parsing_invalid_view_arg(self, testapp):
res = testapp.get("/echo_view_arg/foo", expect_errors=True)
assert res.status_code == 422
assert res.json == {"view_args": {"view_arg": ["Not a valid integer."]}}
def test_use_args_with_view_args_parsing(self, testapp):
res = testapp.get("/echo_view_arg_use_args/42")
assert res.json == {"view_arg": 42}
def test_use_args_on_a_method_view(self, testapp):
res = testapp.post_json("/echo_method_view_use_args", {"val": 42})
assert res.json == {"val": 42}
def test_use_kwargs_on_a_method_view(self, testapp):
res = testapp.post_json("/echo_method_view_use_kwargs", {"val": 42})
assert res.json == {"val": 42}
def test_use_kwargs_with_missing_data(self, testapp):
res = testapp.post_json("/echo_use_kwargs_missing", {"username": "foo"})
assert res.json == {"username": "foo"}
# regression test for https://github.com/marshmallow-code/webargs/issues/145
def test_nested_many_with_data_key(self, testapp):
post_with_raw_fieldname_args = (
"/echo_nested_many_data_key",
{"x_field": [{"id": 42}]},
)
res = testapp.post_json(*post_with_raw_fieldname_args, expect_errors=True)
assert res.status_code == 422
res = testapp.post_json("/echo_nested_many_data_key", {"X-Field": [{"id": 24}]})
assert res.json == {"x_field": [{"id": 24}]}
res = testapp.post_json("/echo_nested_many_data_key", {})
assert res.json == {}
# regression test for https://github.com/marshmallow-code/webargs/issues/500
def test_parsing_unexpected_headers_when_raising(self, testapp):
res = testapp.get(
"/echo_headers_raising", expect_errors=True, headers={"X-Unexpected": "foo"}
)
assert res.status_code == 422
assert "headers" in res.json
assert "X-Unexpected" in set(res.json["headers"].keys())
class TestFlaskAsyncParser(CommonTestCase):
def create_app(self):
return app
@pytest.mark.skipif(
not FLASK_SUPPORTS_ASYNC, reason="requires async support in flask"
)
def test_parsing_view_args_async(self, testapp):
res = testapp.get("/echo_view_arg_async/42")
assert res.json == {"view_arg": 42}
@pytest.mark.skipif(
not FLASK_SUPPORTS_ASYNC, reason="requires async support in flask"
)
def test_parsing_invalid_view_arg_async(self, testapp):
res = testapp.get("/echo_view_arg_async/foo", expect_errors=True)
assert res.status_code == 422
assert res.json == {"view_args": {"view_arg": ["Not a valid integer."]}}
@pytest.mark.skipif(
not FLASK_SUPPORTS_ASYNC, reason="requires async support in flask"
)
def test_use_args_with_view_args_parsing_async(self, testapp):
res = testapp.get("/echo_view_arg_use_args_async/42")
assert res.json == {"view_arg": 42}
@pytest.mark.skipif(
not FLASK_SUPPORTS_ASYNC, reason="requires async support in flask"
)
def test_use_args_on_a_method_view_async(self, testapp):
res = testapp.post_json("/echo_method_view_use_args_async", {"val": 42})
assert res.json == {"val": 42}
@pytest.mark.skipif(
not FLASK_SUPPORTS_ASYNC, reason="requires async support in flask"
)
def test_use_kwargs_on_a_method_view_async(self, testapp):
res = testapp.post_json("/echo_method_view_use_kwargs_async", {"val": 42})
assert res.json == {"val": 42}
@pytest.mark.skipif(
not FLASK_SUPPORTS_ASYNC, reason="requires async support in flask"
)
def test_use_kwargs_with_missing_data_async(self, testapp):
res = testapp.post_json("/echo_use_kwargs_missing_async", {"username": "foo"})
assert res.json == {"username": "foo"}
# regression test for https://github.com/marshmallow-code/webargs/issues/145
@pytest.mark.skipif(
not FLASK_SUPPORTS_ASYNC, reason="requires async support in flask"
)
def test_nested_many_with_data_key_async(self, testapp):
post_with_raw_fieldname_args = (
"/echo_nested_many_data_key_async",
{"x_field": [{"id": 42}]},
)
res = testapp.post_json(*post_with_raw_fieldname_args, expect_errors=True)
assert res.status_code == 422
res = testapp.post_json(
"/echo_nested_many_data_key_async", {"X-Field": [{"id": 24}]}
)
assert res.json == {"x_field": [{"id": 24}]}
res = testapp.post_json("/echo_nested_many_data_key_async", {})
assert res.json == {}
# regression test for https://github.com/marshmallow-code/webargs/issues/500
@pytest.mark.skipif(
not FLASK_SUPPORTS_ASYNC, reason="requires async support in flask"
)
def test_parsing_unexpected_headers_when_raising_async(self, testapp):
res = testapp.get(
"/echo_headers_raising_async",
expect_errors=True,
headers={"X-Unexpected": "foo"},
)
assert res.status_code == 422
assert "headers" in res.json
assert "X-Unexpected" in set(res.json["headers"].keys())
@mock.patch("webargs.flaskparser.abort")
def test_abort_called_on_validation_error(mock_abort):
# error handling must raise an error to be valid
mock_abort.side_effect = BadRequest("foo")
app = Flask("testapp")
def validate(x):
if x != 42:
raise ValidationError("Invalid value.")
argmap = {"value": fields.Raw(validate=validate)}
with app.test_request_context(
"/foo",
method="post",
data=json.dumps({"value": 41}),
content_type="application/json",
):
with pytest.raises(HTTPException):
parser.parse(argmap)
mock_abort.assert_called()
abort_args, abort_kwargs = mock_abort.call_args
assert abort_args[0] == 422
expected_msg = "Invalid value."
assert abort_kwargs["messages"]["json"]["value"] == [expected_msg]
assert type(abort_kwargs["exc"]) is ValidationError
@pytest.mark.asyncio
@pytest.mark.skipif(not FLASK_SUPPORTS_ASYNC, reason="requires async support in flask")
async def test_abort_called_on_validation_error_async():
with mock.patch("webargs.flaskparser.abort") as mock_abort:
# error handling must raise an error to be valid
mock_abort.side_effect = BadRequest("foo")
app = Flask("testapp")
def validate(x):
if x != 42:
raise ValidationError("Invalid value.")
argmap = {"value": fields.Raw(validate=validate)}
with app.test_request_context(
"/foo",
method="post",
data=json.dumps({"value": 41}),
content_type="application/json",
):
with pytest.raises(HTTPException):
await parser.async_parse(argmap)
mock_abort.assert_called()
abort_args, abort_kwargs = mock_abort.call_args
assert abort_args[0] == 422
expected_msg = "Invalid value."
assert abort_kwargs["messages"]["json"]["value"] == [expected_msg]
assert type(abort_kwargs["exc"]) is ValidationError
@pytest.mark.parametrize("mimetype", [None, "application/json"])
def test_load_json_returns_missing_if_no_data(mimetype):
req = mock.Mock()
req.mimetype = mimetype
req.get_data.return_value = ""
schema = Schema.from_dict({"foo": fields.Raw()})()
assert parser.load_json(req, schema) is missing
def test_abort_with_message():
with pytest.raises(HTTPException) as excinfo:
abort(400, message="custom error message")
assert excinfo.value.data["message"] == "custom error message"
def test_abort_has_serializable_data():
with pytest.raises(HTTPException) as excinfo:
abort(400, message="custom error message")
serialized_error = json.dumps(excinfo.value.data)
error = json.loads(serialized_error)
assert isinstance(error, dict)
assert error["message"] == "custom error message"
with pytest.raises(HTTPException) as excinfo:
abort(
400,
message="custom error message",
exc=ValidationError("custom error message"),
)
serialized_error = json.dumps(excinfo.value.data)
error = json.loads(serialized_error)
assert isinstance(error, dict)
assert error["message"] == "custom error message"
|