remove _compat module
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 1263d3b · Browse files · 20 files·+68 added−274 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
20 files+68 added−274 removed
- tests:+13 added−51 removed
- other:+55 added−223 removed
Provenance
- Commit
662c245- Tree
7eaf0ae- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
1263d3b
20 files changed+68 added−274 removed
modified:src/flask/json/__init__.py+5 added-7 removed
14 unmodified lines15 from itsdangerous import json as _json16 from jinja2 import Markup17 from werkzeug.http import http_date18 19-from .._compat import PY220-from .._compat import text_type19 from ..globals import current_app20 from ..globals import request21 22 try:23 import dataclasses24 except ImportError:25+ # Python < 3.726 dataclasses = None27 28 # Figure out if simplejson escapes slashes. This behavior was changed29 # from one version to another without reason.64 unmodified lines94 return str(o)95 if dataclasses and dataclasses.is_dataclass(o):96 return dataclasses.asdict(o)97 if hasattr(o, "__html__"):99- return text_type(o.__html__())98+ return str(o.__html__())99 return _json.JSONEncoder.default(self, o)100 101 102 class JSONDecoder(_json.JSONDecoder):104 unmodified lines207 """208 _dump_arg_defaults(kwargs, app=app)209 encoding = kwargs.pop("encoding", None)210 rv = _json.dumps(obj, **kwargs)212- if encoding is not None and isinstance(rv, text_type):211+ if encoding is not None and isinstance(rv, str):212 rv = rv.encode(encoding)213 return rv214 215 38 unmodified lines254 255 def load(fp, app=None, **kwargs):256 """Like :func:`loads` but reads from a file object."""257 _load_arg_defaults(kwargs, app=app)259- if not PY2:260- fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")258+ fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")259 return _json.load(fp, **kwargs)260 261 262 def htmlsafe_dumps(obj, **kwargs):34 unmodified lines297 298 299 def htmlsafe_dump(obj, fp, **kwargs):300 """Like :func:`htmlsafe_dumps` but writes into a file object."""303- fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))301+ fp.write(str(htmlsafe_dumps(obj, **kwargs)))302 303 304 def jsonify(*args, **kwargs):305 """This function wraps :func:`dumps` to add a few enhancements that make69 unmodified linesmodified:src/flask/json/tag.py+2 added-4 removed
48 unmodified lines49 from jinja2 import Markup50 from werkzeug.http import http_date51 from werkzeug.http import parse_date52 53-from .._compat import iteritems54-from .._compat import text_type53 from ..json import dumps54 from ..json import loads55 56 64 unmodified lines121 122 def to_json(self, value):123 # JSON objects may only have string keys, so don't bother tagging the124 # key here.127- return dict((k, self.serializer.tag(v)) for k, v in iteritems(value))125+ return dict((k, self.serializer.tag(v)) for k, v in value.items())126 127 tag = to_json128 129 48 unmodified lines178 def check(self, value):179 return callable(getattr(value, "__html__", None))180 181 def to_json(self, value):184- return text_type(value.__html__())182+ return str(value.__html__())183 184 def to_python(self, value):185 return Markup(value)186 121 unmodified linesdeleted:src/flask/_compat.py-115 removed
1-# -*- coding: utf-8 -*-2-"""3- flask._compat4- ~~~~~~~~~~~~~5-6- Some py2/py3 compatibility support based on a stripped down7- version of six so we don't have to depend on a specific version8- of it.9-10- :copyright: 2010 Pallets11- :license: BSD-3-Clause12-"""13-import sys14-15-PY2 = sys.version_info[0] == 216-_identity = lambda x: x17-18-try: # Python 219- text_type = unicode20- string_types = (str, unicode)21- integer_types = (int, long)22-except NameError: # Python 323- text_type = str24- string_types = (str,)25- integer_types = (int,)26-27-if not PY2:28- iterkeys = lambda d: iter(d.keys())29- itervalues = lambda d: iter(d.values())30- iteritems = lambda d: iter(d.items())31-32- from inspect import getfullargspec as getargspec33- from io import StringIO34- import collections.abc as collections_abc35-36- def reraise(tp, value, tb=None):37- if value.__traceback__ is not tb:38- raise value.with_traceback(tb)39- raise value40-41- implements_to_string = _identity42-43-else:44- iterkeys = lambda d: d.iterkeys()45- itervalues = lambda d: d.itervalues()46- iteritems = lambda d: d.iteritems()47-48- from inspect import getargspec49- from cStringIO import StringIO50- import collections as collections_abc51-52- exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")53-54- def implements_to_string(cls):55- cls.__unicode__ = cls.__str__56- cls.__str__ = lambda x: x.__unicode__().encode("utf-8")57- return cls58-59-60-def with_metaclass(meta, *bases):61- """Create a base class with a metaclass."""62- # This requires a bit of explanation: the basic idea is to make a63- # dummy metaclass for one level of class instantiation that replaces64- # itself with the actual metaclass.65- class metaclass(type):66- def __new__(metacls, name, this_bases, d):67- return meta(name, bases, d)68-69- return type.__new__(metaclass, "temporary_class", (), {})70-71-72-# Certain versions of pypy have a bug where clearing the exception stack73-# breaks the __exit__ function in a very peculiar way. The second level of74-# exception blocks is necessary because pypy seems to forget to check if an75-# exception happened until the next bytecode instruction?76-#77-# Relevant PyPy bugfix commit:78-# https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df400330179-# According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later80-# versions.81-#82-# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug.83-BROKEN_PYPY_CTXMGR_EXIT = False84-if hasattr(sys, "pypy_version_info"):85-86- class _Mgr(object):87- def __enter__(self):88- return self89-90- def __exit__(self, *args):91- if hasattr(sys, "exc_clear"):92- # Python 3 (PyPy3) doesn't have exc_clear93- sys.exc_clear()94-95- try:96- try:97- with _Mgr():98- raise AssertionError()99- except: # noqa: B001100- # We intentionally use a bare except here. See the comment above101- # regarding a pypy bug as to why.102- raise103- except TypeError:104- BROKEN_PYPY_CTXMGR_EXIT = True105- except AssertionError:106- pass107-108-109-try:110- from os import fspath111-except ImportError:112- # Backwards compatibility as proposed in PEP 0519:113- # https://www.python.org/dev/peps/pep-0519/#backwards-compatibility114- def fspath(path):115- return path.__fspath__() if hasattr(path, "__fspath__") else pathmodified:src/flask/app.py+29 added-41 removed
29 unmodified lines30 from werkzeug.wrappers import BaseResponse31 32 from . import cli33 from . import json34-from ._compat import integer_types35-from ._compat import reraise36-from ._compat import string_types37-from ._compat import text_type34 from .config import Config35 from .config import ConfigAttribute36 from .ctx import _AppCtxGlobals37 from .ctx import AppContext1136 unmodified lines1174 # methods we can use that instead. If neither exists, we go with1175 # a tuple of only ``GET`` as default.1176 if methods is None:1177 methods = getattr(view_func, "methods", None) or ("GET",)1182- if isinstance(methods, string_types):1178+ if isinstance(methods, str):1179 raise TypeError(1184- "Allowed methods have to be iterables of strings, "1185- 'for example: @app.route(..., methods=["POST"])'1180+ "Allowed methods must be a list of strings, for"1181+ ' example: @app.route(..., methods=["POST"])'1182 )1183 methods = set(item.upper() for item in methods)1184 1185 # Methods that should always be added87 unmodified lines1273 1274 :param exc_class_or_code: Any exception class, or an HTTP status1275 code as an integer.1276 """1281- if isinstance(exc_class_or_code, integer_types):1277+ if isinstance(exc_class_or_code, int):1278 exc_class = default_exceptions[exc_class_or_code]1279 else:1280 exc_class = exc_class_or_code1281 440 unmodified lines1722 message.1723 1724 .. versionadded:: 0.71725 """1730- exc_type, exc_value, tb = sys.exc_info()1731- assert exc_value is e1732- # ensure not to trash sys.exc_info() at that point in case someone1733- # wants the traceback preserved in handle_http_exception. Of course1734- # we cannot prevent users from trashing it themselves in a custom1735- # trap_http_exception method so that's their fault then.1736-1726 if isinstance(e, BadRequestKeyError):1727 if self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]:1728 e.show_exception = True1729 10 unmodified lines1740 1741 handler = self._find_error_handler(e)1742 1743 if handler is None:1755- reraise(exc_type, exc_value, tb)1744+ raise1745+1746 return handler(e)1747 1748 def handle_exception(self, e):1749 """Handle an exception that did not have an error handler28 unmodified lines1778 even for the default 500 response when there is no handler.1779 1780 .. versionadded:: 0.31781 """1792- exc_type, exc_value, tb = sys.exc_info()1782+ exc_info = sys.exc_info()1783 got_request_exception.send(self, exception=e)1784 1785 if self.propagate_exceptions:1796- # if we want to repropagate the exception, we can attempt to1797- # raise it with the whole traceback in case we can do that1798- # (the function was actually called from the except part)1799- # otherwise, we just raise the error again1800- if exc_value is e:1801- reraise(exc_type, exc_value, tb)1802- else:1803- raise e1786+ # Re-raise if called with an active exception, otherwise1787+ # raise the passed in exception.1788+ if exc_info[1] is e:1789+ raise1790 1805- self.log_exception((exc_type, exc_value, tb))1791+ raise e1792+1793+ self.log_exception(exc_info)1794 server_error = InternalServerError()1795 # TODO: pass as param when Werkzeug>=1.0.0 is required1796 # TODO: also remove note about this from docstring and docs1797 server_error.original_exception = e215 unmodified lines2013 )2014 2015 # make sure the body is an instance of the response class2016 if not isinstance(rv, self.response_class):2029- if isinstance(rv, (text_type, bytes, bytearray)):2017+ if isinstance(rv, (str, bytes, bytearray)):2018 # let the response class set the status and headers instead of2019 # waiting to do it manually, so that the class can handle any2020 # special logic2021 rv = self.response_class(rv, status=status, headers=headers)5 unmodified lines2027 # class to the correct type2028 try:2029 rv = self.response_class.force_type(rv, request.environ)2030 except TypeError as e:2043- new_error = TypeError(2031+ raise TypeError(2032 "{e}\nThe view function did not return a valid"2033 " response. The return type must be a string, dict, tuple,"2034 " Response instance, or WSGI callable, but it was a"2035 " {rv.__class__.__name__}.".format(e=e, rv=rv)2048- )2049- reraise(TypeError, new_error, sys.exc_info()[2])2036+ ).with_traceback(sys.exc_info()[2])2037 else:2038 raise TypeError(2039 "The view function did not return a valid"2040 " response. The return type must be a string, dict, tuple,"2 unmodified lines2043 )2044 2045 # prefer the status if it was provided2046 if status is not None:2060- if isinstance(status, (text_type, bytes, bytearray)):2047+ if isinstance(status, (str, bytes, bytearray)):2048 rv.status = status2049 else:2050 rv.status_code = status2051 55 unmodified lines2107 for func in funcs:2108 func(endpoint, values)2109 2110 def handle_url_build_error(self, error, endpoint, values):2124- """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.2111+ """Handle :class:`~werkzeug.routing.BuildError` on2112+ :meth:`url_for`.2113 """2126- exc_type, exc_value, tb = sys.exc_info()2114 for handler in self.url_build_error_handlers:2115 try:2116 rv = handler(error, endpoint, values)2130- if rv is not None:2131- return rv2117 except BuildError as e:2133- # make error available outside except block (py3)2118+ # make error available outside except block2119 error = e2120+ else:2121+ if rv is not None:2122+ return rv2123 2136- # At this point we want to reraise the exception. If the error is2137- # still the same one we can reraise it with the original traceback,2138- # otherwise we raise it from here.2139- if error is exc_value:2140- reraise(exc_type, exc_value, tb)2124+ # Re-raise if called with an active exception, otherwise raise2125+ # the passed in exception.2126+ if error is sys.exc_info()[1]:2127+ raise2128+2129 raise error2130 2131 def preprocess_request(self):2132 """Called before the request is dispatched. Calls247 unmodified linesmodified:src/flask/cli.py+5 added-13 removed
23 unmodified lines24 25 import click26 from werkzeug.utils import import_string27 28-from ._compat import getargspec29-from ._compat import itervalues30-from ._compat import reraise31-from ._compat import text_type28 from .globals import current_app29 from .helpers import get_debug_flag30 from .helpers import get_env31 from .helpers import get_load_dotenv26 unmodified lines58 if isinstance(app, Flask):59 return app60 61 # Otherwise find the only object that is a Flask instance.66- matches = [v for v in itervalues(module.__dict__) if isinstance(v, Flask)]62+ matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]63 64 if len(matches) == 1:65 return matches[0]66 elif len(matches) > 1:33 unmodified lines100 """Takes an app factory, a ``script_info` object and optionally a tuple101 of arguments. Checks for the existence of a script_info argument and calls102 the app_factory depending on that and the arguments provided.103 """108- args_spec = getargspec(app_factory)104+ args_spec = inspect.getfullargspec(app_factory)105 arg_names = args_spec.args106 arg_defaults = args_spec.defaults107 108 if "script_info" in arg_names:127 unmodified lines236 __import__(module_name)237 except ImportError:238 # Reraise the ImportError if it occurred within the imported module.239 # Determine this by checking whether the trace has a depth > 1.244- if sys.exc_info()[-1].tb_next:240+ if sys.exc_info()[2].tb_next:241 raise NoAppException(242 'While importing "{name}", an ImportError was raised:'243 "\n\n{tb}".format(name=module_name, tb=traceback.format_exc())244 )77 unmodified lines322 __traceback_hide__ = True # noqa: F841323 exc_info = self._bg_loading_exc_info324 if exc_info is not None:325 self._bg_loading_exc_info = None330- reraise(*exc_info)326+ raise exc_info327 328 def _load_unlocked(self):329 __traceback_hide__ = True # noqa: F841330 self._app = rv = self.loader()405 unmodified lines736 Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.737 """738 cert = ctx.params.get("cert")739 is_adhoc = cert == "adhoc"740+ is_context = ssl and isinstance(cert, ssl.SSLContext)741 745- if sys.version_info < (2, 7, 9):746- is_context = cert and not isinstance(cert, (text_type, bytes))747- else:748- is_context = ssl and isinstance(cert, ssl.SSLContext)749-742 if value is not None:743 if is_adhoc:744 raise click.BadParameter(745 'When "--cert" is "adhoc", "--key" is not used.', ctx, param221 unmodified linesmodified:src/flask/config.py+2 added-5 removed
12 unmodified lines13 import types14 15 from werkzeug.utils import import_string16 17-from ._compat import iteritems18-from ._compat import string_types17 20-18 class ConfigAttribute(object):19 """Makes an attribute forward to the config"""20 21 def __init__(self, name, get_converter=None):143 unmodified lines165 using :meth:`from_object`.166 167 :param obj: an import name or object168 """172- if isinstance(obj, string_types):169+ if isinstance(obj, str):170 obj = import_string(obj)171 for key in dir(obj):172 if key.isupper():173 self[key] = getattr(obj, key)83 unmodified lines257 258 .. versionadded:: 0.11259 """260 rv = {}264- for k, v in iteritems(self):261+ for k, v in self.items():262 if not k.startswith(namespace):263 continue264 if trim_namespace:265 key = k[len(namespace) :]9 unmodified linesmodified:src/flask/ctx.py-8 removed
11 unmodified lines12 from functools import update_wrapper13 14 from werkzeug.exceptions import HTTPException15 16-from ._compat import BROKEN_PYPY_CTXMGR_EXIT17-from ._compat import reraise16 from .globals import _app_ctx_stack17 from .globals import _request_ctx_stack18 from .signals import appcontext_popped19 from .signals import appcontext_pushed225 unmodified lines245 246 def __exit__(self, exc_type, exc_value, tb):247 self.pop(exc_value)248 251- if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:252- reraise(exc_type, exc_value, tb)249 254-250 class RequestContext(object):251 """The request context contains all request relevant information. It is252 created at the beginning of the request and pushed to the253 `_request_ctx_stack` and removed at the end of it. It will create the203 unmodified lines457 # the context can be force kept alive for the test client.458 # See flask.testing for how this works.459 self.auto_pop(exc_value)460 466- if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:467- reraise(exc_type, exc_value, tb)468-461 def __repr__(self):462 return "<%s '%s' [%s] of %s>" % (463 self.__class__.__name__,464 self.request.url,3 unmodified linesmodified:src/flask/debughelpers.py+2 added-5 removed
9 unmodified lines10 """11 import os12 from warnings import warn13 14-from ._compat import implements_to_string15-from ._compat import text_type14 from .app import Flask15 from .blueprints import Blueprint16 from .globals import _request_ctx_stack17 3 unmodified lines21 unexpected unicode or binary data.22 """23 24 27-@implements_to_string25 class DebugFilesKeyError(KeyError, AssertionError):26 """Raised from request.files during debugging. The idea is that it can27 provide a better error message than just a generic KeyError/BadRequest.28 """77 unmodified lines106 for key, value in sorted(loader.__dict__.items()):107 if key.startswith("_"):108 continue109 if isinstance(value, (tuple, list)):113- if not all(isinstance(x, (str, text_type)) for x in value):110+ if not all(isinstance(x, str) for x in value):111 continue112 yield "%s:" % key113 for item in value:114 yield " - %s" % item115 continue119- elif not isinstance(value, (str, text_type, int, float, bool)):116+ elif not isinstance(value, (str, int, float, bool)):117 continue118 yield "%s: %r" % (key, value)119 120 60 unmodified linesmodified:src/flask/helpers.py+7 added-21 removed
28 unmodified lines29 from werkzeug.routing import BuildError30 from werkzeug.urls import url_quote31 from werkzeug.wsgi import wrap_file32 33-from ._compat import fspath34-from ._compat import PY235-from ._compat import string_types36-from ._compat import text_type33 from .globals import _app_ctx_stack34 from .globals import _request_ctx_stack35 from .globals import current_app36 from .globals import request534 unmodified lines571 mtime = None572 fsize = None573 574 if hasattr(filename_or_fp, "__fspath__"):579- filename_or_fp = fspath(filename_or_fp)575+ filename_or_fp = os.fspath(filename_or_fp)576 581- if isinstance(filename_or_fp, string_types):577+ if isinstance(filename_or_fp, str):578 filename = filename_or_fp579 if not os.path.isabs(filename):580 filename = os.path.join(current_app.root_path, filename)581 file = None21 unmodified lines603 if as_attachment:604 if attachment_filename is None:605 raise TypeError("filename unavailable, required for sending as attachment")606 611- if not isinstance(attachment_filename, text_type):607+ if not isinstance(attachment_filename, str):608 attachment_filename = attachment_filename.decode("utf-8")609 610 try:611 attachment_filename = attachment_filename.encode("ascii")1 unmodified line613 filenames = {614 "filename": unicodedata.normalize("NFKD", attachment_filename).encode(615 "ascii", "ignore"616 ),621- "filename*": "UTF-8''%s" % url_quote(attachment_filename, safe=b""),617+ "filename*": "UTF-8''%s" % url_quote(attachment_filename, safe=""),618 }619 else:620 filenames = {"filename": attachment_filename}621 51 unmodified lines673 os.path.getmtime(filename),674 os.path.getsize(filename),675 adler32(676 filename.encode("utf-8")681- if isinstance(filename, text_type)677+ if isinstance(filename, str)678 else filename679 )680 & 0xFFFFFFFF,681 )82 unmodified lines764 download.765 :param options: optional keyword arguments that are directly766 forwarded to :func:`send_file`.767 """772- filename = fspath(filename)773- directory = fspath(directory)768+ filename = os.fspath(filename)769+ directory = os.fspath(directory)770 filename = safe_join(directory, filename)771 if not os.path.isabs(filename):772 filename = os.path.join(current_app.root_path, filename)773 try:361 unmodified lines1135 1136 def is_ip(value):1137 """Determine if the given string is an IP address.1138 1143- Python 2 on Windows doesn't provide ``inet_pton``, so this only1144- checks IPv4 addresses in that environment.1145-1139 :param value: value to check1140 :type value: str1141 1142 :return: True if string is an IP address1143 :rtype: bool1144 """1152- if PY2 and os.name == "nt":1153- try:1154- socket.inet_aton(value)1155- return True1156- except socket.error:1157- return False1158-1145 for family in (socket.AF_INET, socket.AF_INET6):1146 try:1147 socket.inet_pton(family, value)1148 except socket.error:5 unmodified linesmodified:src/flask/sessions.py+2 added-2 removed
8 unmodified lines9 :license: BSD-3-Clause10 """11 import hashlib12 import warnings13+from collections.abc import MutableMapping14 from datetime import datetime15 16 from itsdangerous import BadSignature17 from itsdangerous import URLSafeTimedSerializer18 from werkzeug.datastructures import CallbackDict19 19-from ._compat import collections_abc20 from .helpers import is_ip21 from .helpers import total_seconds22 from .json.tag import TaggedJSONSerializer23 24 25-class SessionMixin(collections_abc.MutableMapping):25+class SessionMixin(MutableMapping):26 """Expands a basic dictionary with session attributes."""27 28 @property29 def permanent(self):365 unmodified linesmodified:src/flask/views.py+1 added-2 removed
6 unmodified lines7 8 :copyright: 2010 Pallets9 :license: BSD-3-Clause10 """11-from ._compat import with_metaclass11 from .globals import request12 13 14 http_method_funcs = frozenset(118 unmodified lines133 if methods:134 cls.methods = methods135 136 138-class MethodView(with_metaclass(MethodViewType, View)):137+class MethodView(View, metaclass=MethodViewType):138 """A class-based view that dispatches request methods to the corresponding139 class methods. For example, if you implement a ``get`` method, it will be140 used to handle ``GET`` requests. ::141 21 unmodified linesmodified:tests/test_basic.py+1 added-2 removed
22 unmodified lines23 from werkzeug.http import parse_date24 from werkzeug.routing import BuildError25 26 import flask27-from flask._compat import text_type27 28 29 def test_options_work(app, client):30 @app.route("/", methods=["GET", "POST"])380 unmodified lines411 return ""412 413 @app.route("/test")414 def test():416- return text_type(flask.session.permanent)415+ return str(flask.session.permanent)416 417 rv = client.get("/")418 assert "set-cookie" in rv.headers419 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])1559 unmodified linesmodified:tests/test_blueprints.py+1 added-2 removed
13 unmodified lines14 from jinja2 import TemplateNotFound15 from werkzeug.http import parse_cache_control_header16 17 import flask18-from flask._compat import text_type18 19 20 def test_blueprint_specific_error_handling(app, client):21 frontend = flask.Blueprint("frontend", __name__)126 unmodified lines148 return "%s/%d" % (bar, baz)149 150 @bp.route("/bar")151 def bar(bar):153- return text_type(bar)152+ return str(bar)153 154 app.register_blueprint(bp, url_prefix="/1", url_defaults={"bar": 23})155 app.register_blueprint(bp, url_prefix="/2", url_defaults={"bar": 19})156 706 unmodified linesmodified:tests/test_config.py-3 removed
12 unmodified lines13 14 import pytest15 16 import flask17-from flask._compat import PY217 18 19 # config keys used for the TestConfig20 TEST_KEY = "foo"175 unmodified lines196 )197 app = flask.Flask(__name__)198 app.config.from_pyfile(str(f))199 value = app.config["TEST_VALUE"]201- if PY2:202- value = value.decode(encoding)200 assert value == u"föö"modified:tests/test_helpers.py+7 added-17 removed
22 unmodified lines23 from werkzeug.http import parse_options_header24 25 import flask26 from flask import json27-from flask._compat import PY228-from flask._compat import StringIO29-from flask._compat import text_type27 from flask.helpers import get_debug_flag28 from flask.helpers import get_env29 30 81 unmodified lines112 113 def test_json_bad_requests(self, app, client):114 @app.route("/json", methods=["POST"])115 def return_json():119- return flask.jsonify(foo=text_type(flask.request.get_json()))116+ return flask.jsonify(foo=str(flask.request.get_json()))117 118 rv = client.post("/json", data="malformed", content_type="application/json")119 assert rv.status_code == 400120 15 unmodified lines136 assert rv == expected137 138 def test_json_dump_to_file(self, app, app_ctx):139 test_data = {"name": "Flask"}143- out = StringIO()140+ out = io.StringIO()141 142 flask.json.dump(test_data, out)143 out.seek(0)144 rv = flask.json.load(out)105 unmodified lines250 def test_json_attr(self, app, client):251 @app.route("/add", methods=["POST"])252 def add():253 json = flask.request.get_json()257- return text_type(json["a"] + json["b"])254+ return str(json["a"] + json["b"])255 256 rv = client.post(257 "/add",258 data=flask.json.dumps({"a": 1, "b": 2}),4 unmodified lines263 def test_template_escaping(self, app, req_ctx):264 render = flask.render_template_string265 rv = flask.json.htmlsafe_dumps("</script>")266 assert rv == u'"\\u003c/script\\u003e"'270- assert type(rv) == text_type267+ assert type(rv) is str268 rv = render('{{ "</script>"|tojson }}')269 assert rv == '"\\u003c/script\\u003e"'270 rv = render('{{ "<\0/script>"|tojson }}')271 assert rv == '"\\u003c\\u0000/script\\u003e"'171 unmodified lines443 except AssertionError:444 assert lines == sorted_by_str445 446 450-class PyStringIO(object):447+class PyBytesIO(object):448 def __init__(self, *args, **kwargs):449 self._io = io.BytesIO(*args, **kwargs)450 451 def __getattr__(self, name):47 unmodified lines499 "opener",500 [501 lambda app: open(os.path.join(app.static_folder, "index.html"), "rb"),502 lambda app: io.BytesIO(b"Test"),506- pytest.param(507- lambda app: StringIO("Test"),508- marks=pytest.mark.skipif(not PY2, reason="Python 2 only"),509- ),510- lambda app: PyStringIO(b"Test"),503+ lambda app: PyBytesIO(b"Test"),504 ],505 )506 @pytest.mark.usefixtures("req_ctx")507 def test_send_file_object(self, app, opener):9 unmodified lines517 @pytest.mark.parametrize(518 "opener",519 [520 lambda app: io.StringIO(u"Test"),528- pytest.param(529- lambda app: open(os.path.join(app.static_folder, "index.html")),521+ lambda app: open(os.path.join(app.static_folder, "index.html")),530- marks=pytest.mark.skipif(PY2, reason="Python 3 only"),531- ),522 ],523 )524 @pytest.mark.usefixtures("req_ctx")525 def test_send_file_text_fails(self, app, opener):508 unmodified linesmodified:tests/test_instance_config.py-17 removed
10 unmodified lines11 12 import pytest13 14 import flask15-from flask._compat import PY215 16 17 def test_explicit_instance_paths(modules_tmpdir):18 with pytest.raises(ValueError) as excinfo:107 unmodified lines126 )127 finally:128 if "site_egg" in sys.modules:129 del sys.modules["site_egg"]131-132-133-@pytest.mark.skipif(not PY2, reason="This only works under Python 2.")134-def test_meta_path_loader_without_is_package(request, modules_tmpdir):135- app = modules_tmpdir.join("unimportable.py")136- app.write("import flask\napp = flask.Flask(__name__)")137-138- class Loader(object):139- def find_module(self, name, path=None):140- return self141-142- sys.meta_path.append(Loader())143- request.addfinalizer(sys.meta_path.pop)144-145- with pytest.raises(AttributeError):146- import unimportable # noqa: F401modified:tests/test_logging.py+1 added-1 removed
6 unmodified lines7 :license: BSD-3-Clause8 """9 import logging10 import sys11+from io import StringIO12 13 import pytest14 14-from flask._compat import StringIO15 from flask.logging import default_handler16 from flask.logging import has_level_handler17 from flask.logging import wsgi_errors_stream18 88 unmodified linesdeleted:tests/test_meta.py-6 removed
1-import io2-3-4-def test_changelog_utf8_compatible():5- with io.open("CHANGES.rst", encoding="UTF-8") as f:6- f.read()modified:tests/test_subclassing.py+2 added-1 removed
7 unmodified lines8 9 :copyright: 2010 Pallets10 :license: BSD-3-Clause11 """12+from io import StringIO13+14 import flask13-from flask._compat import StringIO15 16 17 def test_suppressed_exception_logging():18 class SuppressedFlask(flask.Flask):14 unmodified linesmodified:tests/test_testing.py+1 added-2 removed
12 unmodified lines13 import werkzeug14 15 import flask16 from flask import appcontext_popped17-from flask._compat import text_type17 from flask.cli import ScriptInfo18 from flask.json import jsonify19 from flask.testing import EnvironBuilder20 from flask.testing import FlaskCliRunner161 unmodified lines182 183 def test_session_transactions(app, client):184 @app.route("/")185 def index():187- return text_type(flask.session["foo"])186+ return str(flask.session["foo"])187 188 with client:189 with client.session_transaction() as sess:190 assert len(sess) == 0246 unmodified lines