Skip to content

Commit

Permalink
Address or ignore warnings raised in tests (#918)
Browse files Browse the repository at this point in the history
* Address or ignore warnings raised in tests

* Use importlib to get django version, for consistency
  • Loading branch information
sloria committed Jan 31, 2024
1 parent 4907006 commit 07ca302
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 38 deletions.
10 changes: 10 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,13 @@ select = [
"UP", # pyupgrade
"W", # pycodestyle warning
]

[tool.pytest.ini_options]
filterwarnings = [
# https://github.com/Pylons/pyramid/issues/3731
"ignore:.*pkg_resources.*:DeprecationWarning",
# https://github.com/Pylons/webob/issues/437
"ignore:.*'cgi' is deprecated.*:DeprecationWarning",
# https://github.com/sloria/webtest-aiohttp/issues/6
"ignore:.*The object should be created within an async function.*:DeprecationWarning",
]
4 changes: 2 additions & 2 deletions tests/apps/django_app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django import __version__
import importlib.metadata

DJANGO_MAJOR_VERSION = int(__version__.split(".")[0])
DJANGO_MAJOR_VERSION = int(importlib.metadata.version("django").split(".")[0])
DJANGO_SUPPORTS_ASYNC = DJANGO_MAJOR_VERSION >= 3
67 changes: 42 additions & 25 deletions tests/apps/falcon_app.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import importlib.metadata

import falcon
import marshmallow as ma

Expand All @@ -8,7 +10,7 @@
hello_args = {"name": fields.Str(load_default="World", validate=lambda n: len(n) >= 3)}
hello_multiple = {"name": fields.List(fields.Str())}

FALCON_MAJOR_VERSION = int(falcon.__version__.split(".")[0])
FALCON_MAJOR_VERSION = int(importlib.metadata.version("falcon").split(".")[0])
FALCON_SUPPORTS_ASYNC = FALCON_MAJOR_VERSION >= 3


Expand All @@ -22,58 +24,65 @@ class HelloSchema(ma.Schema):
hello_exclude_schema = HelloSchema(unknown=ma.EXCLUDE)


def set_text(resp, value):
if FALCON_MAJOR_VERSION >= 3:
resp.text = value
else:
resp.body = value


class Echo:
def on_get(self, req, resp):
parsed = parser.parse(hello_args, req, location="query")
resp.body = json.dumps(parsed)
set_text(resp, json.dumps(parsed))


class AsyncEcho:
async def on_get(self, req, resp):
parsed = await parser.async_parse(hello_args, req, location="query")
resp.body = json.dumps(parsed)
set_text(resp, json.dumps(parsed))


class EchoForm:
def on_post(self, req, resp):
parsed = parser.parse(hello_args, req, location="form")
resp.body = json.dumps(parsed)
set_text(resp, json.dumps(parsed))


class EchoJSON:
def on_post(self, req, resp):
parsed = parser.parse(hello_args, req, location="json")
resp.body = json.dumps(parsed)
set_text(resp, json.dumps(parsed))


class EchoMedia:
def on_post(self, req, resp):
parsed = parser.parse(hello_args, req, location="media")
resp.body = json.dumps(parsed)
set_text(resp, json.dumps(parsed))


class EchoJSONOrForm:
def on_post(self, req, resp):
parsed = parser.parse(hello_args, req, location="json_or_form")
resp.body = json.dumps(parsed)
set_text(resp, json.dumps(parsed))


class EchoUseArgs:
@use_args(hello_args, location="query")
def on_get(self, req, resp, args):
resp.body = json.dumps(args)
set_text(resp, json.dumps(args))


class AsyncEchoUseArgs:
@use_args(hello_args, location="query")
async def on_get(self, req, resp, args):
resp.body = json.dumps(args)
set_text(resp, json.dumps(args))


class EchoUseKwargs:
@use_kwargs(hello_args, location="query")
def on_get(self, req, resp, name):
resp.body = json.dumps({"name": name})
set_text(resp, json.dumps({"name": name}))


class EchoUseArgsValidated:
Expand All @@ -83,44 +92,46 @@ class EchoUseArgsValidated:
location="form",
)
def on_post(self, req, resp, args):
resp.body = json.dumps(args)
set_text(resp, json.dumps(args))


class EchoJSONIgnoreExtraData:
def on_post(self, req, resp):
resp.body = json.dumps(parser.parse(hello_exclude_schema, req, unknown=None))
set_text(
resp, json.dumps(parser.parse(hello_exclude_schema, req, unknown=None))
)


class EchoMulti:
def on_get(self, req, resp):
resp.body = json.dumps(parser.parse(hello_multiple, req, location="query"))
set_text(resp, json.dumps(parser.parse(hello_multiple, req, location="query")))


class EchoMultiForm:
def on_post(self, req, resp):
resp.body = json.dumps(parser.parse(hello_multiple, req, location="form"))
set_text(resp, json.dumps(parser.parse(hello_multiple, req, location="form")))


class EchoMultiJSON:
def on_post(self, req, resp):
resp.body = json.dumps(parser.parse(hello_multiple, req))
set_text(resp, json.dumps(parser.parse(hello_multiple, req)))


class EchoManySchema:
def on_post(self, req, resp):
resp.body = json.dumps(parser.parse(hello_many_schema, req))
set_text(resp, json.dumps(parser.parse(hello_many_schema, req)))


class EchoUseArgsWithPathParam:
@use_args({"value": fields.Int()}, location="query")
def on_get(self, req, resp, args, name):
resp.body = json.dumps(args)
set_text(resp, json.dumps(args))


class EchoUseKwargsWithPathParam:
@use_kwargs({"value": fields.Int()}, location="query")
def on_get(self, req, resp, value, name):
resp.body = json.dumps({"value": value})
set_text(resp, json.dumps({"value": value}))


class AlwaysError:
Expand All @@ -129,7 +140,7 @@ def always_fail(value):
raise ma.ValidationError("something went wrong")

args = {"text": fields.Str(validate=always_fail)}
resp.body = json.dumps(parser.parse(args, req))
set_text(resp, json.dumps(parser.parse(args, req)))

on_post = on_get

Expand All @@ -139,18 +150,20 @@ def on_get(self, req, resp):
class HeaderSchema(ma.Schema):
NAME = fields.Str(load_default="World")

resp.body = json.dumps(parser.parse(HeaderSchema(), req, location="headers"))
set_text(
resp, json.dumps(parser.parse(HeaderSchema(), req, location="headers"))
)


class EchoCookie:
def on_get(self, req, resp):
resp.body = json.dumps(parser.parse(hello_args, req, location="cookies"))
set_text(resp, json.dumps(parser.parse(hello_args, req, location="cookies")))


class EchoNested:
def on_post(self, req, resp):
args = {"name": fields.Nested({"first": fields.Str(), "last": fields.Str()})}
resp.body = json.dumps(parser.parse(args, req))
set_text(resp, json.dumps(parser.parse(args, req)))


class EchoNestedMany:
Expand All @@ -160,7 +173,7 @@ def on_post(self, req, resp):
{"id": fields.Int(), "name": fields.Str()}, many=True
)
}
resp.body = json.dumps(parser.parse(args, req))
set_text(resp, json.dumps(parser.parse(args, req)))


def use_args_hook(args, context_key="args", **kwargs):
Expand All @@ -174,11 +187,15 @@ def hook(req, resp, resource, params):
@falcon.before(use_args_hook(hello_args, location="query"))
class EchoUseArgsHook:
def on_get(self, req, resp):
resp.body = json.dumps(req.context["args"])
set_text(resp, json.dumps(req.context["args"]))


def create_app():
app = falcon.API()
if FALCON_MAJOR_VERSION >= 3:
app = falcon.App()
else:
app = falcon.API()

app.add_route("/echo", Echo())
app.add_route("/echo_form", EchoForm())
app.add_route("/echo_json", EchoJSON())
Expand Down
5 changes: 3 additions & 2 deletions tests/apps/flask_app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import importlib.metadata

import marshmallow as ma
from flask import Flask, Response, request
from flask import __version__ as flask_version
from flask import jsonify as J
from flask.views import MethodView

Expand All @@ -12,7 +13,7 @@
use_kwargs,
)

FLASK_MAJOR_VERSION = int(flask_version.split(".")[0])
FLASK_MAJOR_VERSION = int(importlib.metadata.version("flask").split(".")[0])
FLASK_SUPPORTS_ASYNC = FLASK_MAJOR_VERSION >= 2


Expand Down
10 changes: 6 additions & 4 deletions tests/test_aiohttpparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ class TestAIOHTTPParser(CommonTestCase):
def create_app(self):
return create_app()

def create_testapp(self, app, loop):
return webtest_aiohttp.TestApp(app, loop=loop)
def create_testapp(self, app, event_loop):
return webtest_aiohttp.TestApp(app, loop=event_loop)

@pytest.fixture
def testapp(self, loop):
return self.create_testapp(self.create_app(), loop)
def testapp(self, event_loop):
return self.create_testapp(self.create_app(), event_loop)

@pytest.mark.skip(reason="files location not supported for aiohttpparser")
def test_parse_files(self, testapp):
Expand Down Expand Up @@ -84,6 +84,7 @@ def test_validation_error_returns_422_response(self, testapp):
assert res.json == {"json": {"name": ["Invalid value."]}}


@pytest.mark.asyncio
async def test_aiohttpparser_synchronous_error_handler(web_request):
parser = AIOHTTPParser()

Expand All @@ -100,6 +101,7 @@ def custom_handle_error(error, req, schema, *, error_status_code, error_headers)
)


@pytest.mark.asyncio
async def test_aiohttpparser_asynchronous_error_handler(web_request):
parser = AIOHTTPParser()

Expand Down
9 changes: 6 additions & 3 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,8 +315,10 @@ def test_arg_with_default_and_location(parser, web_request):
"p": fields.Int(
load_default=1,
validate=lambda p: p > 0,
error="La page demandée n'existe pas",
location="querystring",
metadata={
"error": "La page demandée n'existe pas",
"location": "querystring",
},
)
}
assert parser.parse(args, web_request) == {"p": 1}
Expand Down Expand Up @@ -692,6 +694,7 @@ def viewfunc(args):
assert viewfunc() == {"username": "foo", "password": "bar"}


@pytest.mark.asyncio
async def test_use_args_on_async(web_request, parser):
user_args = {"username": fields.Str(), "password": fields.Str()}
web_request.json = {"username": "foo", "password": "bar"}
Expand Down Expand Up @@ -1260,7 +1263,7 @@ def test_validation_errors_in_validator_are_passed_to_handle_error(parser, web_r
def validate(value):
raise ValidationError("Something went wrong.")

args = {"name": fields.Field(validate=validate, location="json")}
args = {"name": fields.Field(validate=validate, metadata={"location": "json"})}
web_request.json = {"name": "invalid"}
with pytest.raises(ValidationError) as excinfo:
parser.parse(args, web_request)
Expand Down
5 changes: 3 additions & 2 deletions tests/test_tornadoparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,11 @@ def test_it_should_not_include_fieldnames_if_not_present(self):
result = parser.load_json(request, author_schema)
assert result == {}

def test_it_should_handle_type_error_on_load_json(self, loop):
@pytest.mark.usefixtures("event_loop")
def test_it_should_handle_type_error_on_load_json(self):
# but this is different from the test above where the payload was valid
# and empty -- missing vs {}
# NOTE: `loop` is the pytest-aiohttp event loop fixture, but it's
# NOTE: `event_loop` is the pytest-aiohttp event loop fixture, but it's
# important to get an event loop here so that we can construct a future
request = make_request(
body=tornado.concurrent.Future(),
Expand Down

0 comments on commit 07ca302

Please sign in to comment.