diff --git a/docs/wiki-example-code/example.py b/docs/wiki-example-code/example.py index f5edd9f4..fa1ee961 100644 --- a/docs/wiki-example-code/example.py +++ b/docs/wiki-example-code/example.py @@ -55,7 +55,6 @@ class WikiApp(object): - view_template = VIEW_TEMPLATE edit_template = EDIT_TEMPLATE @@ -72,7 +71,7 @@ def __call__(self, environ, start_response): except AttributeError: raise exc.HTTPBadRequest("No such action %r" % action) resp = meth(req, page) - except exc.HTTPException, e: + except exc.HTTPException as e: resp = e return resp(environ, start_response) diff --git a/src/webob/acceptparse.py b/src/webob/acceptparse.py index b186dad6..63141e0c 100644 --- a/src/webob/acceptparse.py +++ b/src/webob/acceptparse.py @@ -1221,7 +1221,7 @@ def parse(value): try: parsed_accepted = Accept.parse(value) - for (media, q, _, _) in parsed_accepted: + for media, q, _, _ in parsed_accepted: yield (media, q) except ValueError: pass diff --git a/src/webob/cookies.py b/src/webob/cookies.py index ed20327a..4c141e28 100644 --- a/src/webob/cookies.py +++ b/src/webob/cookies.py @@ -30,7 +30,6 @@ class RequestCookies(MutableMapping): - _cache_key = "webob._parsed_cookies" def __init__(self, environ): diff --git a/src/webob/exc.py b/src/webob/exc.py index 23652e12..f2812051 100644 --- a/src/webob/exc.py +++ b/src/webob/exc.py @@ -230,7 +230,6 @@ def __call__(self, environ, start_response): class WSGIHTTPException(Response, HTTPException): - # You should set in subclasses: # code = 200 # title = 'OK' diff --git a/src/webob/request.py b/src/webob/request.py index 20d7a25d..ee52a7d1 100644 --- a/src/webob/request.py +++ b/src/webob/request.py @@ -83,7 +83,6 @@ class BaseRequest: _charset = None def __init__(self, environ, **kw): - if type(environ) is not dict: raise TypeError(f"WSGI environ must be a dict; you passed {environ!r}") diff --git a/tests/test_client.py b/tests/test_client.py index de9635e1..ea3aa785 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,9 +1,10 @@ import io import socket -import unittest +import pytest -class TestSendRequest(unittest.TestCase): + +class TestSendRequest: def _getTargetClass(self): from webob.client import SendRequest @@ -30,7 +31,7 @@ def _makeEnviron(self, extra=None): def test___call___unknown_scheme(self): environ = self._makeEnviron({"wsgi.url_scheme": "abc"}) inst = self._makeOne() - self.assertRaises(ValueError, inst, environ, None) + pytest.raises(ValueError, inst, environ, None) def test___call___gardenpath(self): environ = self._makeEnviron() @@ -39,13 +40,13 @@ def test___call___gardenpath(self): inst = self._makeOne(HTTPConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "200 OK") - self.assertEqual(headers, []) + assert status == "200 OK" + assert headers == [] inst.start_response_called = True iterable = inst(environ, start_response) - self.assertTrue(inst.start_response_called) - self.assertEqual(list(iterable), [b"foo"]) + assert inst.start_response_called + assert list(iterable) == [b"foo"] def test___call___no_servername_no_http_host(self): environ = self._makeEnviron() @@ -54,7 +55,7 @@ def test___call___no_servername_no_http_host(self): response = DummyResponse("msg") conn_factory = DummyConnectionFactory(response) inst = self._makeOne(HTTPConnection=conn_factory) - self.assertRaises(ValueError, inst, environ, None) + pytest.raises(ValueError, inst, environ, None) def test___call___no_servername_colon_not_in_host_http(self): environ = self._makeEnviron() @@ -65,15 +66,15 @@ def test___call___no_servername_colon_not_in_host_http(self): inst = self._makeOne(HTTPConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "200 OK") - self.assertEqual(headers, []) + assert status == "200 OK" + assert headers == [] inst.start_response_called = True iterable = inst(environ, start_response) - self.assertTrue(inst.start_response_called) - self.assertEqual(list(iterable), [b"foo"]) - self.assertEqual(environ["SERVER_NAME"], "localhost") - self.assertEqual(environ["SERVER_PORT"], "80") + assert inst.start_response_called + assert list(iterable) == [b"foo"] + assert environ["SERVER_NAME"] == "localhost" + assert environ["SERVER_PORT"] == "80" def test___call___no_servername_colon_not_in_host_https(self): environ = self._makeEnviron() @@ -85,15 +86,15 @@ def test___call___no_servername_colon_not_in_host_https(self): inst = self._makeOne(HTTPSConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "200 OK") - self.assertEqual(headers, []) + assert status == "200 OK" + assert headers == [] inst.start_response_called = True iterable = inst(environ, start_response) - self.assertTrue(inst.start_response_called) - self.assertEqual(list(iterable), [b"foo"]) - self.assertEqual(environ["SERVER_NAME"], "localhost") - self.assertEqual(environ["SERVER_PORT"], "443") + assert inst.start_response_called + assert list(iterable) == [b"foo"] + assert environ["SERVER_NAME"] == "localhost" + assert environ["SERVER_PORT"] == "443" def test___call___no_content_length(self): environ = self._makeEnviron() @@ -103,13 +104,13 @@ def test___call___no_content_length(self): inst = self._makeOne(HTTPConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "200 OK") - self.assertEqual(headers, []) + assert status == "200 OK" + assert headers == [] inst.start_response_called = True iterable = inst(environ, start_response) - self.assertTrue(inst.start_response_called) - self.assertEqual(list(iterable), [b"foo"]) + assert inst.start_response_called + assert list(iterable) == [b"foo"] def test___call___with_webob_client_timeout_and_timeout_supported(self): environ = self._makeEnviron() @@ -119,14 +120,14 @@ def test___call___with_webob_client_timeout_and_timeout_supported(self): inst = self._makeOne(HTTPConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "200 OK") - self.assertEqual(headers, []) + assert status == "200 OK" + assert headers == [] inst.start_response_called = True iterable = inst(environ, start_response) - self.assertTrue(inst.start_response_called) - self.assertEqual(list(iterable), [b"foo"]) - self.assertEqual(conn_factory.kw, {"timeout": 10}) + assert inst.start_response_called + assert list(iterable) == [b"foo"] + assert conn_factory.kw == {"timeout": 10} def test___call___bad_content_length(self): environ = self._makeEnviron({"CONTENT_LENGTH": "abc"}) @@ -135,13 +136,13 @@ def test___call___bad_content_length(self): inst = self._makeOne(HTTPConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "200 OK") - self.assertEqual(headers, []) + assert status == "200 OK" + assert headers == [] inst.start_response_called = True iterable = inst(environ, start_response) - self.assertTrue(inst.start_response_called) - self.assertEqual(list(iterable), [b"foo"]) + assert inst.start_response_called + assert list(iterable) == [b"foo"] def test___call___with_socket_timeout(self): environ = self._makeEnviron() @@ -151,12 +152,12 @@ def test___call___with_socket_timeout(self): inst = self._makeOne(HTTPConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "504 Gateway Timeout") + assert status == "504 Gateway Timeout" inst.start_response_called = True iterable = inst(environ, start_response) - self.assertTrue(inst.start_response_called) - self.assertTrue(list(iterable)[0].startswith(b"504")) + assert inst.start_response_called + assert list(iterable)[0].startswith(b"504") def test___call___with_socket_error_neg2(self): environ = self._makeEnviron() @@ -165,12 +166,12 @@ def test___call___with_socket_error_neg2(self): inst = self._makeOne(HTTPConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "502 Bad Gateway") + assert status == "502 Bad Gateway" inst.start_response_called = True iterable = inst(environ, start_response) - self.assertTrue(inst.start_response_called) - self.assertTrue(list(iterable)[0].startswith(b"502")) + assert inst.start_response_called + assert list(iterable)[0].startswith(b"502") def test___call___with_socket_error_ENODATA(self): import errno @@ -184,12 +185,12 @@ def test___call___with_socket_error_ENODATA(self): inst = self._makeOne(HTTPConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "502 Bad Gateway") + assert status == "502 Bad Gateway" inst.start_response_called = True iterable = inst(environ, start_response) - self.assertTrue(inst.start_response_called) - self.assertTrue(list(iterable)[0].startswith(b"502")) + assert inst.start_response_called + assert list(iterable)[0].startswith(b"502") def test___call___with_socket_error_unknown(self): environ = self._makeEnviron() @@ -198,10 +199,10 @@ def test___call___with_socket_error_unknown(self): inst = self._makeOne(HTTPConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "502 Bad Gateway") + assert status == "502 Bad Gateway" inst.start_response_called = True - self.assertRaises(socket.error, inst, environ, start_response) + pytest.raises(socket.error, inst, environ, start_response) def test___call___nolength(self): environ = self._makeEnviron() @@ -210,14 +211,14 @@ def test___call___nolength(self): inst = self._makeOne(HTTPConnection=conn_factory) def start_response(status, headers): - self.assertEqual(status, "200 OK") - self.assertEqual(headers, []) + assert status == "200 OK" + assert headers == [] inst.start_response_called = True iterable = inst(environ, start_response) - self.assertTrue(inst.start_response_called) - self.assertEqual(list(iterable), [b"foo"]) - self.assertEqual(response.length, None) + assert inst.start_response_called + assert list(iterable) == [b"foo"] + assert response.length == None class DummyMessage: diff --git a/tests/test_compat.py b/tests/test_compat.py index 245117a1..9c9f87ea 100644 --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -1,11 +1,10 @@ from io import BytesIO import sys -import unittest import pytest -class text_Tests(unittest.TestCase): +class TestText: def _callFUT(self, *arg, **kw): from webob.util import text_ @@ -13,24 +12,24 @@ def _callFUT(self, *arg, **kw): def test_binary(self): result = self._callFUT(b"123") - self.assertTrue(isinstance(result, str)) - self.assertEqual(result, str(b"123", "ascii")) + assert isinstance(result, str) + assert result == str(b"123", "ascii") def test_binary_alternate_decoding(self): result = self._callFUT(b"La Pe\xc3\xb1a", "utf-8") - self.assertTrue(isinstance(result, str)) - self.assertEqual(result, str(b"La Pe\xc3\xb1a", "utf-8")) + assert isinstance(result, str) + assert result == str(b"La Pe\xc3\xb1a", "utf-8") def test_binary_decoding_error(self): - self.assertRaises(UnicodeDecodeError, self._callFUT, b"\xff", "utf-8") + pytest.raises(UnicodeDecodeError, self._callFUT, b"\xff", "utf-8") def test_text(self): result = self._callFUT(str(b"123", "ascii")) - self.assertTrue(isinstance(result, str)) - self.assertEqual(result, str(b"123", "ascii")) + assert isinstance(result, str) + assert result == str(b"123", "ascii") -class bytes_Tests(unittest.TestCase): +class TestBytes: def _callFUT(self, *arg, **kw): from webob.util import bytes_ @@ -38,20 +37,20 @@ def _callFUT(self, *arg, **kw): def test_binary(self): result = self._callFUT(b"123") - self.assertTrue(isinstance(result, bytes)) - self.assertEqual(result, b"123") + assert isinstance(result, bytes) + assert result == b"123" def test_text(self): val = str(b"123", "ascii") result = self._callFUT(val) - self.assertTrue(isinstance(result, bytes)) - self.assertEqual(result, b"123") + assert isinstance(result, bytes) + assert result == b"123" def test_text_alternate_encoding(self): val = str(b"La Pe\xc3\xb1a", "utf-8") result = self._callFUT(val, "utf-8") - self.assertTrue(isinstance(result, bytes)) - self.assertEqual(result, b"La Pe\xc3\xb1a") + assert isinstance(result, bytes) + assert result == b"La Pe\xc3\xb1a" class Test_cgi_FieldStorage_Py3_tests: diff --git a/tests/test_dec.py b/tests/test_dec.py index de9c685f..4bf930fa 100644 --- a/tests/test_dec.py +++ b/tests/test_dec.py @@ -1,4 +1,4 @@ -import unittest +import pytest from webob.dec import wsgify from webob.request import Request @@ -6,7 +6,7 @@ from webob.util import bytes_, text_ -class DecoratorTests(unittest.TestCase): +class TestDecorator: def _testit(self, app, req): if isinstance(req, str): req = Request.blank(req) @@ -22,13 +22,13 @@ def test_app(req): return bytes_(resp_str % req.url) resp = self._testit(test_app, "/a url") - self.assertEqual(resp.body, bytes_(resp_str % "http://localhost/a%20url")) - self.assertEqual(resp.content_length, 45) - self.assertEqual(resp.content_type, "text/html") - self.assertEqual(resp.charset, "UTF-8") + assert resp.body == bytes_(resp_str % "http://localhost/a%20url") + assert resp.content_length == 45 + assert resp.content_type == "text/html" + assert resp.charset == "UTF-8" def test_wsgify_empty_repr(self): - self.assertTrue("wsgify at" in repr(wsgify())) + assert "wsgify at" in repr(wsgify()) def test_wsgify_args(self): resp_str = b"hey hey my my" @@ -38,10 +38,10 @@ def test_app(req, strarg): return strarg resp = self._testit(test_app, "/a url") - self.assertEqual(resp.body, resp_str) - self.assertEqual(resp.content_length, 13) - self.assertEqual(resp.content_type, "text/html") - self.assertEqual(resp.charset, "UTF-8") + assert resp.body == resp_str + assert resp.content_length == 13 + assert resp.content_type == "text/html" + assert resp.charset == "UTF-8" def test_wsgify_kwargs(self): resp_str = b"hey hey my my" @@ -51,10 +51,10 @@ def test_app(req, strarg=""): return strarg resp = self._testit(test_app, "/a url") - self.assertEqual(resp.body, resp_str) - self.assertEqual(resp.content_length, 13) - self.assertEqual(resp.content_type, "text/html") - self.assertEqual(resp.charset, "UTF-8") + assert resp.body == resp_str + assert resp.content_length == 13 + assert resp.content_type == "text/html" + assert resp.charset == "UTF-8" def test_wsgify_raise_httpexception(self): from webob.exc import HTTPBadRequest @@ -64,9 +64,9 @@ def test_app(req): raise HTTPBadRequest resp = self._testit(test_app, "/a url") - self.assertTrue(resp.body.startswith(b"400 Bad Request")) - self.assertEqual(resp.content_type, "text/plain") - self.assertEqual(resp.charset, "UTF-8") + assert resp.body.startswith(b"400 Bad Request") + assert resp.content_type == "text/plain" + assert resp.charset == "UTF-8" def test_wsgify_no___get__(self): # use a class instance instead of a fn so we wrap something w/ @@ -77,8 +77,8 @@ def __call__(self, req): test_app = wsgify(TestApp()) resp = self._testit(test_app, "/a url") - self.assertEqual(resp.body, b"nothing to see here") - self.assertTrue(test_app.__get__(test_app) is test_app) + assert resp.body == b"nothing to see here" + assert test_app.__get__(test_app) is test_app def test_wsgify_app_returns_unicode(self): def test_app(req): @@ -86,11 +86,11 @@ def test_app(req): test_app = wsgify(test_app) resp = self._testit(test_app, "/a url") - self.assertEqual(resp.body, b"some text") + assert resp.body == b"some text" def test_wsgify_args_no_func(self): test_app = wsgify(None, args=(1,)) - self.assertRaises(TypeError, self._testit, test_app, "/a url") + pytest.raises(TypeError, self._testit, test_app, "/a url") def test_wsgify_call_args(self): resp_str = "args: %s, kwargs: %s" @@ -101,9 +101,7 @@ def show_vars(req, *args, **kwargs): app = wsgify(show_vars, args=("foo", "bar"), kwargs={"a": 1, "b": 2}) resp = app(Request.blank("/")) - self.assertEqual( - resp, bytes_(resp_str % ("['bar', 'foo']", "[('a', 1), ('b', 2)]")) - ) + assert resp == bytes_(resp_str % ("['bar', 'foo']", "[('a', 1), ('b', 2)]")) def test_wsgify_call_args_override(self): resp_str = "args: %s, kwargs: %s" @@ -114,7 +112,7 @@ def show_vars(req, *args, **kwargs): app = wsgify(show_vars, args=("foo", "bar"), kwargs={"a": 1, "b": 2}) resp = app(Request.blank("/"), "qux", c=3) - self.assertEqual(resp, bytes_(resp_str % ("['qux']", "[('c', 3)]"))) + assert resp == bytes_(resp_str % ("['qux']", "[('c', 3)]")) def test_wsgify_wrong_sig(self): @wsgify @@ -122,8 +120,8 @@ def test_app(req): return "What have you done for me lately?" req = dict() - self.assertRaises(TypeError, test_app, req, 1, 2) - self.assertRaises(TypeError, test_app, req, 1, key="word") + pytest.raises(TypeError, test_app, req, 1, 2) + pytest.raises(TypeError, test_app, req, 1, key="word") def test_wsgify_none_response(self): @wsgify @@ -131,9 +129,9 @@ def test_app(req): return resp = self._testit(test_app, "/a url") - self.assertEqual(resp.body, b"") - self.assertEqual(resp.content_type, "text/html") - self.assertEqual(resp.content_length, 0) + assert resp.body == b"" + assert resp.content_type == "text/html" + assert resp.content_length == 0 def test_wsgify_get(self): resp_str = b"What'choo talkin' about, Willis?" @@ -143,7 +141,7 @@ def test_app(req): return Response(resp_str) resp = test_app.get("/url/path") - self.assertEqual(resp.body, resp_str) + assert resp.body == resp_str def test_wsgify_post(self): post_dict = dict(speaker="Robin", words="Holy test coverage, Batman!") @@ -153,8 +151,8 @@ def test_app(req): return Response("{}: {}".format(req.POST["speaker"], req.POST["words"])) resp = test_app.post("/url/path", post_dict) - self.assertEqual( - resp.body, bytes_("{}: {}".format(post_dict["speaker"], post_dict["words"])) + assert resp.body == bytes_( + "{}: {}".format(post_dict["speaker"], post_dict["words"]) ) def test_wsgify_request_method(self): @@ -162,21 +160,21 @@ def test_wsgify_request_method(self): @wsgify def test_app(req): - self.assertEqual(req.method, "PUT") + assert req.method == "PUT" return Response(req.body) resp = test_app.request("/url/path", method="PUT", body=resp_str) - self.assertEqual(resp.body, resp_str) - self.assertEqual(resp.content_length, 10) - self.assertEqual(resp.content_type, "text/html") + assert resp.body == resp_str + assert resp.content_length == 10 + assert resp.content_type == "text/html" def test_wsgify_undecorated(self): def test_app(req): return Response("whoa") wrapped_test_app = wsgify(test_app) - self.assertTrue(wrapped_test_app.undecorated is test_app) + assert wrapped_test_app.undecorated is test_app def test_wsgify_custom_request(self): resp_str = "hey, this is a test: %s" @@ -189,10 +187,10 @@ def test_app(req): return bytes_(resp_str % req.url) resp = self._testit(test_app, "/a url") - self.assertEqual(resp.body, bytes_(resp_str % "http://localhost/a%20url")) - self.assertEqual(resp.content_length, 45) - self.assertEqual(resp.content_type, "text/html") - self.assertEqual(resp.charset, "UTF-8") + assert resp.body == bytes_(resp_str % "http://localhost/a%20url") + assert resp.content_length == 45 + assert resp.content_type == "text/html" + assert resp.charset == "UTF-8" def test_middleware(self): resp_str = "These are the vars: %s" @@ -205,9 +203,9 @@ def set_urlvar(req, app, **vars): from webob.dec import _MiddlewareFactory - self.assertTrue(set_urlvar.__class__ is _MiddlewareFactory) + assert set_urlvar.__class__ is _MiddlewareFactory r = repr(set_urlvar) - self.assertTrue("set_urlvar" in r) + assert "set_urlvar" in r @wsgify def show_vars(req): @@ -215,10 +213,10 @@ def show_vars(req): show_vars2 = set_urlvar(show_vars, a=1, b=2) resp = self._testit(show_vars2, "/path") - self.assertEqual(resp.body, bytes_(resp_str % "[('a', 1), ('b', 2)]")) - self.assertEqual(resp.content_type, "text/html") - self.assertEqual(resp.charset, "UTF-8") - self.assertEqual(resp.content_length, 40) + assert resp.body == bytes_(resp_str % "[('a', 1), ('b', 2)]") + assert resp.content_type == "text/html" + assert resp.charset == "UTF-8" + assert resp.content_length == 40 def test_middleware_call_kwargs(self): resp_str = "kwargs: %s" @@ -236,7 +234,7 @@ def show_vars(req): app = set_args(show_vars, a=1, b=2) resp = app(Request.blank("/")) - self.assertEqual(resp.body, bytes_(resp_str % "[('a', 1), ('b', 2)]")) + assert resp.body == bytes_(resp_str % "[('a', 1), ('b', 2)]") def test_middleware_call_kwargs_override(self): resp_str = "kwargs: %s" @@ -254,7 +252,7 @@ def show_vars(req): app = set_args(show_vars, a=1, b=2) resp = app(Request.blank("/"), c=3) - self.assertEqual(resp.body, bytes_(resp_str % "[('c', 3)]")) + assert resp.body == bytes_(resp_str % "[('c', 3)]") def test_middleware_as_decorator(self): resp_str = "These are the vars: %s" @@ -271,10 +269,10 @@ def show_vars(req): return resp_str % (sorted(req.urlvars.items())) resp = self._testit(show_vars, "/path") - self.assertEqual(resp.body, bytes_(resp_str % "[('a', 1), ('b', 2)]")) - self.assertEqual(resp.content_type, "text/html") - self.assertEqual(resp.charset, "UTF-8") - self.assertEqual(resp.content_length, 40) + assert resp.body == bytes_(resp_str % "[('a', 1), ('b', 2)]") + assert resp.content_type == "text/html" + assert resp.charset == "UTF-8" + assert resp.content_length == 40 def test_unbound_middleware(self): @wsgify @@ -284,22 +282,22 @@ def test_app(req): unbound = wsgify.middleware(None, test_app, some="thing") from webob.dec import _UnboundMiddleware - self.assertTrue(unbound.__class__ is _UnboundMiddleware) - self.assertEqual(unbound.kw, dict(some="thing")) + assert unbound.__class__ is _UnboundMiddleware + assert unbound.kw == dict(some="thing") @unbound def middle(req, app, **kw): return app(req) - self.assertTrue(middle.__class__ is wsgify) - self.assertTrue("test_app" in repr(unbound)) + assert middle.__class__ is wsgify + assert "test_app" in repr(unbound) def test_unbound_middleware_no_app(self): unbound = wsgify.middleware(None, None) from webob.dec import _UnboundMiddleware - self.assertTrue(unbound.__class__ is _UnboundMiddleware) - self.assertEqual(unbound.kw, dict()) + assert unbound.__class__ is _UnboundMiddleware + assert unbound.kw == dict() def test_classapp(self): class HostMap(dict): @@ -311,10 +309,10 @@ def __call__(self, req): app["example.com"] = Response("1") app["other.com"] = Response("2") resp = Request.blank("http://example.com/").get_response(wsgify(app)) - self.assertEqual(resp.content_type, "text/html") - self.assertEqual(resp.charset, "UTF-8") - self.assertEqual(resp.content_length, 1) - self.assertEqual(resp.body, b"1") + assert resp.content_type == "text/html" + assert resp.charset == "UTF-8" + assert resp.content_length == 1 + assert resp.body == b"1" def test_middleware_direct_call(self): @wsgify.middleware @@ -322,4 +320,4 @@ def mw(req, app): return "foo" app = mw(Response()) - self.assertEqual(app(Request.blank("/")), "foo") + assert app(Request.blank("/")) == "foo" diff --git a/tests/test_multidict.py b/tests/test_multidict.py index 1d04bad3..00d4e638 100644 --- a/tests/test_multidict.py +++ b/tests/test_multidict.py @@ -1,11 +1,11 @@ -import unittest +import pytest from webob import multidict from webob.util import text_ class BaseDictTests: - def setUp(self): + def setup_method(self, method): self._list = [("a", text_("\xe9")), ("a", "e"), ("a", "f"), ("b", "1")] self.data = multidict.MultiDict(self._list) self.d = self._get_instance() @@ -18,142 +18,140 @@ def _get_instance(self, **kwargs): return self.klass(data) def test_len(self): - self.assertEqual(len(self.d), 4) + assert len(self.d) == 4 def test_getone(self): - self.assertEqual(self.d.getone("b"), "1") + assert self.d.getone("b") == "1" def test_getone_missing(self): - self.assertRaises(KeyError, self.d.getone, "z") + pytest.raises(KeyError, self.d.getone, "z") def test_getone_multiple_raises(self): - self.assertRaises(KeyError, self.d.getone, "a") + pytest.raises(KeyError, self.d.getone, "a") def test_getall(self): - self.assertEqual(list(self.d.getall("b")), ["1"]) + assert list(self.d.getall("b")) == ["1"] def test_dict_of_lists(self): - self.assertEqual( - self.d.dict_of_lists(), {"a": [text_("\xe9"), "e", "f"], "b": ["1"]} - ) + assert self.d.dict_of_lists() == {"a": [text_("\xe9"), "e", "f"], "b": ["1"]} def test_dict_api(self): - self.assertTrue("a" in self.d.mixed()) - self.assertTrue("a" in self.d.keys()) - self.assertTrue(("b", "1") in self.d.items()) - self.assertTrue("1" in self.d.values()) - self.assertEqual(len(self.d), 4) + assert "a" in self.d.mixed() + assert "a" in self.d.keys() + assert ("b", "1") in self.d.items() + assert "1" in self.d.values() + assert len(self.d) == 4 def test_set_del_item(self): d = self._get_instance() - self.assertTrue("a" in d) + assert "a" in d del d["a"] - self.assertTrue("a" not in d) + assert "a" not in d def test_pop(self): d = self._get_instance() d["a"] = "1" - self.assertEqual(d.pop("a"), "1") - self.assertEqual(d.pop("x", "1"), "1") + assert d.pop("a") == "1" + assert d.pop("x", "1") == "1" def test_pop_wrong_args(self): d = self._get_instance() - self.assertRaises(TypeError, d.pop, "a", "1", "1") + pytest.raises(TypeError, d.pop, "a", "1", "1") def test_pop_missing(self): d = self._get_instance() - self.assertRaises(KeyError, d.pop, "z") + pytest.raises(KeyError, d.pop, "z") def test_popitem(self): d = self._get_instance() - self.assertEqual(d.popitem(), ("b", "1")) + assert d.popitem() == ("b", "1") def test_update(self): d = self._get_instance() d.update(e="1") - self.assertTrue("e" in d) + assert "e" in d d.update(dict(x="1")) - self.assertTrue("x" in d) + assert "x" in d d.update([("y", "1")]) - self.assertTrue("y" in d) + assert "y" in d def test_setdefault(self): d = self._get_instance() d.setdefault("a", "1") - self.assertNotEqual(d["a"], "1") + assert d["a"] != "1" d.setdefault("e", "1") - self.assertTrue("e" in d) + assert "e" in d def test_add(self): d = multidict.MultiDict({"a": "1"}) d.add("a", "2") - self.assertEqual(list(d.getall("a")), ["1", "2"]) + assert list(d.getall("a")) == ["1", "2"] d = self._get_instance() d.add("b", "3") - self.assertEqual(list(d.getall("b")), ["1", "3"]) + assert list(d.getall("b")) == ["1", "3"] def test_copy(self): assert self.d.copy() is not self.d if hasattr(self.d, "multi"): - self.assertFalse(self.d.copy().multi is self.d.multi) - self.assertFalse(self.d.copy() is self.d.multi) + assert not self.d.copy().multi is self.d.multi + assert not self.d.copy() is self.d.multi def test_clear(self): d = self._get_instance() d.clear() - self.assertEqual(len(d), 0) + assert len(d) == 0 def test_nonzero(self): d = self._get_instance() - self.assertTrue(d) + assert d d.clear() - self.assertFalse(d) + assert not d def test_repr(self): - self.assertTrue(repr(self._get_instance())) + assert repr(self._get_instance()) def test_too_many_args(self): from webob.multidict import MultiDict - self.assertRaises(TypeError, MultiDict, "1", 2) + pytest.raises(TypeError, MultiDict, "1", 2) def test_no_args(self): from webob.multidict import MultiDict md = MultiDict() - self.assertEqual(md._items, []) + assert md._items == [] def test_kwargs(self): from webob.multidict import MultiDict md = MultiDict(kw1="val1") - self.assertEqual(md._items, [("kw1", "val1")]) + assert md._items == [("kw1", "val1")] def test_view_list_not_list(self): from webob.multidict import MultiDict d = MultiDict() - self.assertRaises(TypeError, d.view_list, 42) + pytest.raises(TypeError, d.view_list, 42) def test_view_list(self): from webob.multidict import MultiDict d = MultiDict() - self.assertEqual(d.view_list([1, 2])._items, [1, 2]) + assert d.view_list([1, 2])._items == [1, 2] def test_from_fieldstorage_with_filename(self): from webob.multidict import MultiDict d = MultiDict() fs = DummyFieldStorage("a", "1", "file") - self.assertEqual(d.from_fieldstorage(fs), MultiDict({"a": fs.list[0]})) + assert d.from_fieldstorage(fs) == MultiDict({"a": fs.list[0]}) def test_from_fieldstorage_without_filename(self): from webob.multidict import MultiDict d = MultiDict() fs = DummyFieldStorage("a", "1") - self.assertEqual(d.from_fieldstorage(fs), MultiDict({"a": "1"})) + assert d.from_fieldstorage(fs) == MultiDict({"a": "1"}) def test_from_fieldstorage_with_charset(self): from cgi import FieldStorage @@ -180,9 +178,7 @@ def test_from_fieldstorage_with_charset(self): environ.update(CONTENT_LENGTH=len(body)) fs = FieldStorage(multipart_body, environ=environ) vars = MultiDict.from_fieldstorage(fs) - self.assertEqual( - vars["title"].encode("utf8"), text_("こんにちは", "utf8").encode("utf8") - ) + assert vars["title"].encode("utf8") == text_("こんにちは", "utf8").encode("utf8") def test_from_fieldstorage_with_base64_encoding(self): from cgi import FieldStorage @@ -210,9 +206,7 @@ def test_from_fieldstorage_with_base64_encoding(self): environ.update(CONTENT_LENGTH=len(body)) fs = FieldStorage(multipart_body, environ=environ) vars = MultiDict.from_fieldstorage(fs) - self.assertEqual( - vars["title"].encode("utf8"), text_("こんにちは", "utf8").encode("utf8") - ) + assert vars["title"].encode("utf8") == text_("こんにちは", "utf8").encode("utf8") def test_from_fieldstorage_with_quoted_printable_encoding(self): from cgi import FieldStorage @@ -240,12 +234,10 @@ def test_from_fieldstorage_with_quoted_printable_encoding(self): environ.update(CONTENT_LENGTH=len(body)) fs = FieldStorage(multipart_body, environ=environ) vars = MultiDict.from_fieldstorage(fs) - self.assertEqual( - vars["title"].encode("utf8"), text_("こんにちは", "utf8").encode("utf8") - ) + assert vars["title"].encode("utf8") == text_("こんにちは", "utf8").encode("utf8") -class MultiDictTestCase(BaseDictTests, unittest.TestCase): +class TestMultiDict(BaseDictTests): klass = multidict.MultiDict def test_update_behavior_warning(self): @@ -260,23 +252,23 @@ def __len__(self): d = self._get_instance() with warnings.catch_warnings(record=True) as w: d.update(foo) - self.assertEqual(len(w), 1) + assert len(w) == 1 def test_repr_with_password(self): d = self._get_instance(password="pwd") - self.assertEqual(repr(d), "MultiDict([('password', '******')])") + assert repr(d) == "MultiDict([('password', '******')])" -class NestedMultiDictTestCase(BaseDictTests, unittest.TestCase): +class TestNestedMultiDict(BaseDictTests): klass = multidict.NestedMultiDict def test_getitem(self): d = self.klass({"a": 1}) - self.assertEqual(d["a"], 1) + assert d["a"] == 1 def test_getitem_raises(self): d = self._get_instance() - self.assertRaises(KeyError, d.__getitem__, "z") + pytest.raises(KeyError, d.__getitem__, "z") def test_contains(self): d = self._get_instance() @@ -285,49 +277,49 @@ def test_contains(self): def test_add(self): d = self._get_instance() - self.assertRaises(KeyError, d.add, "b", 3) + pytest.raises(KeyError, d.add, "b", 3) def test_set_del_item(self): d = self._get_instance() - self.assertRaises(KeyError, d.__delitem__, "a") - self.assertRaises(KeyError, d.__setitem__, "a", 1) + pytest.raises(KeyError, d.__delitem__, "a") + pytest.raises(KeyError, d.__setitem__, "a", 1) def test_update(self): d = self._get_instance() - self.assertRaises(KeyError, d.update, e=1) - self.assertRaises(KeyError, d.update, dict(x=1)) - self.assertRaises(KeyError, d.update, [("y", 1)]) + pytest.raises(KeyError, d.update, e=1) + pytest.raises(KeyError, d.update, dict(x=1)) + pytest.raises(KeyError, d.update, [("y", 1)]) def test_setdefault(self): d = self._get_instance() - self.assertRaises(KeyError, d.setdefault, "a", 1) + pytest.raises(KeyError, d.setdefault, "a", 1) def test_pop(self): d = self._get_instance() - self.assertRaises(KeyError, d.pop, "a") - self.assertRaises(KeyError, d.pop, "a", 1) + pytest.raises(KeyError, d.pop, "a") + pytest.raises(KeyError, d.pop, "a", 1) def test_popitem(self): d = self._get_instance() - self.assertRaises(KeyError, d.popitem, "a") + pytest.raises(KeyError, d.popitem, "a") def test_pop_wrong_args(self): d = self._get_instance() - self.assertRaises(KeyError, d.pop, "a", 1, 1) + pytest.raises(KeyError, d.pop, "a", 1, 1) def test_clear(self): d = self._get_instance() - self.assertRaises(KeyError, d.clear) + pytest.raises(KeyError, d.clear) def test_nonzero(self): d = self._get_instance() - self.assertEqual(d.__nonzero__(), True) + assert d.__nonzero__() == True d.dicts = [{}] - self.assertEqual(d.__nonzero__(), False) + assert d.__nonzero__() == False assert not d -class TestGetDict(BaseDictTests, unittest.TestCase): +class TestGetDict(BaseDictTests): klass = multidict.GetDict def _get_instance(self, environ=None, **kwargs): @@ -348,13 +340,13 @@ def items(self): d = self._get_instance() d._items = None d.__init__(Arg(), lambda: None) - self.assertEqual(self.d._items, self._list) + assert self.d._items == self._list def test_nullextend(self): d = self._get_instance() - self.assertEqual(d.extend(), None) + assert d.extend() == None d.extend(test="a") - self.assertEqual(d["test"], "a") + assert d["test"] == "a" def test_extend_from_items(self): values = {"a": "1", "b": "2", "c": "3"} @@ -365,7 +357,7 @@ def items(self): d = self._get_instance() d.extend(MappingWithItems()) - self.assertTrue(set(values.items()).issubset(d._items)) + assert set(values.items()).issubset(d._items) def test_extend_from_keys(self): values = {"a": "1", "b": "2", "c": "3"} @@ -379,75 +371,75 @@ def keys(self): d = self._get_instance() d.extend(MappingWithoutItems()) - self.assertTrue(set(values.items()).issubset(d._items)) + assert set(values.items()).issubset(d._items) def test_extend_from_iterable(self): items = [("a", "1")] d = self._get_instance() d.extend(iter(items)) - self.assertTrue(set(items).issubset(d._items)) + assert set(items).issubset(d._items) def test_repr_with_password(self): d = self._get_instance(password="pwd") - self.assertEqual(repr(d), "GET([('password', '******')])") + assert repr(d) == "GET([('password', '******')])" def test_setitem_updates_QUERY_STRING(self): env = {} d = self._get_instance(environ=env) d["a"] = "2" - self.assertEqual(env["QUERY_STRING"], "b=1&a=2") + assert env["QUERY_STRING"] == "b=1&a=2" def test_add_updates_QUERY_STRING(self): env = {} d = self._get_instance(environ=env) d.add("a", "2") - self.assertEqual(env["QUERY_STRING"], "a=%C3%A9&a=e&a=f&b=1&a=2") + assert env["QUERY_STRING"] == "a=%C3%A9&a=e&a=f&b=1&a=2" def test_delitem_updates_QUERY_STRING(self): env = {} d = self._get_instance(environ=env) del d["a"] - self.assertEqual(env["QUERY_STRING"], "b=1") + assert env["QUERY_STRING"] == "b=1" def test_clear_updates_QUERY_STRING(self): env = {} d = self._get_instance(environ=env) d.clear() - self.assertEqual(env["QUERY_STRING"], "") + assert env["QUERY_STRING"] == "" def test_setdefault_updates_QUERY_STRING(self): env = {} d = self._get_instance(environ=env) d.setdefault("c", "2") - self.assertEqual(env["QUERY_STRING"], "a=%C3%A9&a=e&a=f&b=1&c=2") + assert env["QUERY_STRING"] == "a=%C3%A9&a=e&a=f&b=1&c=2" def test_pop_updates_QUERY_STRING(self): env = {} d = self._get_instance(environ=env) d.pop("a") - self.assertEqual(env["QUERY_STRING"], "a=e&a=f&b=1") + assert env["QUERY_STRING"] == "a=e&a=f&b=1" def test_popitem_updates_QUERY_STRING(self): env = {} d = self._get_instance(environ=env) d.popitem() - self.assertEqual(env["QUERY_STRING"], "a=%C3%A9&a=e&a=f") + assert env["QUERY_STRING"] == "a=%C3%A9&a=e&a=f" def test_update_updates_QUERY_STRING(self): env = {} d = self._get_instance(environ=env) d.update([("a", "2")]) - self.assertEqual(env["QUERY_STRING"], "b=1&a=2") + assert env["QUERY_STRING"] == "b=1&a=2" def test_extend_updates_QUERY_STRING(self): env = {} d = self._get_instance(environ=env) d.extend([("a", "2")]) - self.assertEqual(env["QUERY_STRING"], "a=%C3%A9&a=e&a=f&b=1&a=2") + assert env["QUERY_STRING"] == "a=%C3%A9&a=e&a=f&b=1&a=2" -class NoVarsTestCase(unittest.TestCase): +class TestNoVars: klass = multidict.NoVars def _get_instance(self): @@ -455,31 +447,31 @@ def _get_instance(self): def test_getitem(self): d = self._get_instance() - self.assertRaises(KeyError, d.__getitem__, "a") + pytest.raises(KeyError, d.__getitem__, "a") def test_setitem(self): d = self._get_instance() - self.assertRaises(KeyError, d.__setitem__, "a") + pytest.raises(KeyError, d.__setitem__, "a") def test_delitem(self): d = self._get_instance() - self.assertRaises(KeyError, d.__delitem__, "a") + pytest.raises(KeyError, d.__delitem__, "a") def test_get(self): d = self._get_instance() - self.assertEqual(d.get("a", default="b"), "b") + assert d.get("a", default="b") == "b" def test_getall(self): d = self._get_instance() - self.assertEqual(d.getall("a"), []) + assert d.getall("a") == [] def test_getone(self): d = self._get_instance() - self.assertRaises(KeyError, d.getone, "a") + pytest.raises(KeyError, d.getone, "a") def test_mixed(self): d = self._get_instance() - self.assertEqual(d.mixed(), {}) + assert d.mixed() == {} def test_contains(self): d = self._get_instance() @@ -487,19 +479,19 @@ def test_contains(self): def test_copy(self): d = self._get_instance() - self.assertEqual(d.copy(), d) + assert d.copy() == d def test_len(self): d = self._get_instance() - self.assertEqual(len(d), 0) + assert len(d) == 0 def test_repr(self): d = self._get_instance() - self.assertEqual(repr(d), "") + assert repr(d) == "" def test_keys(self): d = self._get_instance() - self.assertEqual(list(d.keys()), []) + assert list(d.keys()) == [] class DummyField: diff --git a/tests/test_response.py b/tests/test_response.py index ed2b7f19..f0b82085 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -1103,7 +1103,7 @@ def test_location_unicode(): res.location = "/test.html" def start_response(status, headerlist): - for (header, val) in headerlist: + for header, val in headerlist: if header.lower() == "location": assert val == "http://test.com/test.html" assert isinstance(val, str) diff --git a/tests/test_static.py b/tests/test_static.py index 0d8ad2ed..a3d364c0 100644 --- a/tests/test_static.py +++ b/tests/test_static.py @@ -4,7 +4,8 @@ import shutil import tempfile from time import gmtime -import unittest + +import pytest from webob import static from webob.request import Request, environ_from_url @@ -28,8 +29,8 @@ def create_file(content, *paths): return path -class TestFileApp(unittest.TestCase): - def setUp(self): +class TestFileApp: + def setup_method(self, method): fp = tempfile.NamedTemporaryFile(suffix=".py", delete=False) self.tempfile = fp.name fp.write(b"import this\n") @@ -42,30 +43,24 @@ def test_fileapp(self): app = static.FileApp(self.tempfile) resp1 = get_response(app) assert resp1.content_type in ("text/x-python", "text/plain") - self.assertEqual(resp1.charset, "UTF-8") - self.assertEqual( - resp1.last_modified.timetuple(), gmtime(getmtime(self.tempfile)) - ) - self.assertEqual(resp1.body, b"import this\n") + assert resp1.charset == "UTF-8" + assert resp1.last_modified.timetuple() == gmtime(getmtime(self.tempfile)) + assert resp1.body == b"import this\n" resp2 = get_response(app) assert resp2.content_type in ("text/x-python", "text/plain") - self.assertEqual( - resp2.last_modified.timetuple(), gmtime(getmtime(self.tempfile)) - ) - self.assertEqual(resp2.body, b"import this\n") + assert resp2.last_modified.timetuple() == gmtime(getmtime(self.tempfile)) + assert resp2.body == b"import this\n" resp3 = get_response(app, range=(7, 11)) - self.assertEqual(resp3.status_code, 206) - self.assertEqual(tuple(resp3.content_range)[:2], (7, 11)) - self.assertEqual( - resp3.last_modified.timetuple(), gmtime(getmtime(self.tempfile)) - ) - self.assertEqual(resp3.body, bytes_("this")) + assert resp3.status_code == 206 + assert tuple(resp3.content_range)[:2] == (7, 11) + assert resp3.last_modified.timetuple() == gmtime(getmtime(self.tempfile)) + assert resp3.body == bytes_("this") def test_unexisting_file(self): app = static.FileApp("/tmp/this/doesnt/exist") - self.assertEqual(404, get_response(app).status_code) + assert 404 == get_response(app).status_code def test_allowed_methods(self): app = static.FileApp(self.tempfile) @@ -74,11 +69,11 @@ def test_allowed_methods(self): def resp(method): return get_response(app, method=method) - self.assertEqual(200, resp(method="GET").status_code) - self.assertEqual(200, resp(method="HEAD").status_code) - self.assertEqual(405, resp(method="POST").status_code) + assert 200 == resp(method="GET").status_code + assert 200 == resp(method="HEAD").status_code + assert 405 == resp(method="POST").status_code # Actually any other method is not allowed - self.assertEqual(405, resp(method="xxx").status_code) + assert 405 == resp(method="xxx").status_code def test_exception_while_opening_file(self): # Mock the built-in ``open()`` function to allow finner control about @@ -92,10 +87,10 @@ def open_oserror(*args, **kwargs): app = static.FileApp(self.tempfile) app._open = open_ioerror - self.assertEqual(403, get_response(app).status_code) + assert 403 == get_response(app).status_code app._open = open_oserror - self.assertEqual(403, get_response(app).status_code) + assert 403 == get_response(app).status_code def test_use_wsgi_filewrapper(self): class TestWrapper: @@ -110,46 +105,46 @@ def __init__(self, file, block_size): app = static.FileApp(self.tempfile) app_iter = Request(environ).get_response(app).app_iter - self.assertTrue(isinstance(app_iter, TestWrapper)) - self.assertEqual(bytes_("import this\n"), app_iter.file.read()) - self.assertEqual(static.BLOCK_SIZE, app_iter.block_size) + assert isinstance(app_iter, TestWrapper) + assert bytes_("import this\n") == app_iter.file.read() + assert static.BLOCK_SIZE == app_iter.block_size -class TestFileIter(unittest.TestCase): +class TestFileIter: def test_empty_file(self): fp = BytesIO() fi = static.FileIter(fp) - self.assertRaises(StopIteration, next, iter(fi)) + pytest.raises(StopIteration, next, iter(fi)) def test_seek(self): fp = BytesIO(bytes_("0123456789")) i = static.FileIter(fp).app_iter_range(seek=4) - self.assertEqual(bytes_("456789"), next(i)) - self.assertRaises(StopIteration, next, i) + assert bytes_("456789") == next(i) + pytest.raises(StopIteration, next, i) def test_limit(self): fp = BytesIO(bytes_("0123456789")) i = static.FileIter(fp).app_iter_range(limit=4) - self.assertEqual(bytes_("0123"), next(i)) - self.assertRaises(StopIteration, next, i) + assert bytes_("0123") == next(i) + pytest.raises(StopIteration, next, i) def test_limit_and_seek(self): fp = BytesIO(bytes_("0123456789")) i = static.FileIter(fp).app_iter_range(limit=4, seek=1) - self.assertEqual(bytes_("123"), next(i)) - self.assertRaises(StopIteration, next, i) + assert bytes_("123") == next(i) + pytest.raises(StopIteration, next, i) def test_multiple_reads(self): fp = BytesIO(bytes_("012")) i = static.FileIter(fp).app_iter_range(block_size=1) - self.assertEqual(bytes_("0"), next(i)) - self.assertEqual(bytes_("1"), next(i)) - self.assertEqual(bytes_("2"), next(i)) - self.assertRaises(StopIteration, next, i) + assert bytes_("0") == next(i) + assert bytes_("1") == next(i) + assert bytes_("2") == next(i) + pytest.raises(StopIteration, next, i) def test_seek_bigger_than_limit(self): fp = BytesIO(bytes_("0123456789")) @@ -157,18 +152,18 @@ def test_seek_bigger_than_limit(self): # XXX: this should not return anything actually, since we are starting # to read after the place we wanted to stop. - self.assertEqual(bytes_("23456789"), next(i)) - self.assertRaises(StopIteration, next, i) + assert bytes_("23456789") == next(i) + pytest.raises(StopIteration, next, i) def test_limit_is_zero(self): fp = BytesIO(bytes_("0123456789")) i = static.FileIter(fp).app_iter_range(limit=0) - self.assertRaises(StopIteration, next, i) + pytest.raises(StopIteration, next, i) -class TestDirectoryApp(unittest.TestCase): - def setUp(self): +class TestDirectoryApp: + def setup_method(self, method): self.test_dir = tempfile.mkdtemp() def tearDown(self): @@ -176,18 +171,18 @@ def tearDown(self): def test_empty_directory(self): app = static.DirectoryApp(self.test_dir) - self.assertEqual(404, get_response(app).status_code) - self.assertEqual(404, get_response(app, "/foo").status_code) + assert 404 == get_response(app).status_code + assert 404 == get_response(app, "/foo").status_code def test_serve_file(self): app = static.DirectoryApp(self.test_dir) create_file("abcde", self.test_dir, "bar") - self.assertEqual(404, get_response(app).status_code) - self.assertEqual(404, get_response(app, "/foo").status_code) + assert 404 == get_response(app).status_code + assert 404 == get_response(app, "/foo").status_code resp = get_response(app, "/bar") - self.assertEqual(200, resp.status_code) - self.assertEqual(bytes_("abcde"), resp.body) + assert 200 == resp.status_code + assert bytes_("abcde") == resp.body def test_dont_serve_file_in_parent_directory(self): # We'll have: @@ -200,7 +195,7 @@ def test_dont_serve_file_in_parent_directory(self): app = static.DirectoryApp(serve_path) # The file exists, but is outside the served dir. - self.assertEqual(403, get_response(app, "/../bar").status_code) + assert 403 == get_response(app, "/../bar").status_code def test_dont_leak_parent_directory_file_existance(self): # We'll have: @@ -211,15 +206,15 @@ def test_dont_leak_parent_directory_file_existance(self): app = static.DirectoryApp(serve_path) # The file exists, but is outside the served dir. - self.assertEqual(403, get_response(app, "/../bar2").status_code) + assert 403 == get_response(app, "/../bar2").status_code def test_file_app_arguments(self): app = static.DirectoryApp(self.test_dir, content_type="xxx/yyy") create_file("abcde", self.test_dir, "bar") resp = get_response(app, "/bar") - self.assertEqual(200, resp.status_code) - self.assertEqual("xxx/yyy", resp.content_type) + assert 200 == resp.status_code + assert "xxx/yyy" == resp.content_type def test_file_app_factory(self): def make_fileapp(*args, **kwargs): @@ -234,33 +229,33 @@ def make_fileapp(*args, **kwargs): create_file("abcde", self.test_dir, "bar") get_response(app, "/bar") - self.assertTrue(make_fileapp.called) + assert make_fileapp.called def test_must_serve_directory(self): serve_path = create_file("abcde", self.test_dir, "bar") - self.assertRaises(IOError, static.DirectoryApp, serve_path) + pytest.raises(IOError, static.DirectoryApp, serve_path) def test_index_page(self): os.mkdir(os.path.join(self.test_dir, "index-test")) create_file(bytes_("index"), self.test_dir, "index-test", "index.html") app = static.DirectoryApp(self.test_dir) resp = get_response(app, "/index-test") - self.assertEqual(resp.status_code, 301) - self.assertTrue(resp.location.endswith("/index-test/")) + assert resp.status_code == 301 + assert resp.location.endswith("/index-test/") resp = get_response(app, "/index-test?test") - self.assertTrue(resp.location.endswith("/index-test/?test")) + assert resp.location.endswith("/index-test/?test") resp = get_response(app, "/index-test/") - self.assertEqual(resp.status_code, 200) - self.assertEqual(resp.body, bytes_("index")) - self.assertEqual(resp.content_type, "text/html") + assert resp.status_code == 200 + assert resp.body == bytes_("index") + assert resp.content_type == "text/html" resp = get_response(app, "/index-test/index.html") - self.assertEqual(resp.status_code, 200) - self.assertEqual(resp.body, bytes_("index")) + assert resp.status_code == 200 + assert resp.body == bytes_("index") redir_app = static.DirectoryApp(self.test_dir, hide_index_with_redirect=True) resp = get_response(redir_app, "/index-test/index.html") - self.assertEqual(resp.status_code, 301) - self.assertTrue(resp.location.endswith("/index-test/")) + assert resp.status_code == 301 + assert resp.location.endswith("/index-test/") resp = get_response(redir_app, "/index-test/index.html?test") - self.assertTrue(resp.location.endswith("/index-test/?test")) + assert resp.location.endswith("/index-test/?test") page_app = static.DirectoryApp(self.test_dir, index_page="something-else.html") - self.assertEqual(get_response(page_app, "/index-test/").status_code, 404) + assert get_response(page_app, "/index-test/").status_code == 404 diff --git a/tests/test_util.py b/tests/test_util.py index 3f71f2b8..84f0cacc 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -1,24 +1,22 @@ -import unittest import warnings +import pytest + from webob.response import Response from webob.util import warn_deprecation -class Test_warn_deprecation(unittest.TestCase): - def setUp(self): - +class Test_warn_deprecation: + def setup_method(self, method): self.oldwarn = warnings.warn warnings.warn = self._warn self.warnings = [] def tearDown(self): - warnings.warn = self.oldwarn del self.warnings def _callFUT(self, text, version, stacklevel): - return warn_deprecation(text, version, stacklevel) def _warn(self, text, type, stacklevel=1): @@ -28,24 +26,24 @@ def test_multidict_update_warning(self): # test warning when duplicate keys are passed r = Response() r.headers.update([("Set-Cookie", "a=b"), ("Set-Cookie", "x=y")]) - self.assertEqual(len(self.warnings), 1) + assert len(self.warnings) == 1 deprecation_warning = self.warnings[0] - self.assertEqual(deprecation_warning["type"], UserWarning) + assert deprecation_warning["type"] == UserWarning assert "Consider using .extend()" in deprecation_warning["text"] def test_multidict_update_warning_unnecessary(self): # no warning on normal operation r = Response() r.headers.update([("Set-Cookie", "a=b")]) - self.assertEqual(len(self.warnings), 0) + assert len(self.warnings) == 0 def test_warn_deprecation(self): v = "1.3.0" - self.assertRaises(DeprecationWarning, warn_deprecation, "foo", v[:3], 1) + pytest.raises(DeprecationWarning, warn_deprecation, "foo", v[:3], 1) def test_warn_deprecation_future_version(self): v = "9.9.9" warn_deprecation("foo", v[:3], 1) - self.assertEqual(len(self.warnings), 1) + assert len(self.warnings) == 1