Skip to content
Myr

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

20 files+68 added−274 removed

modified:src/flask/json/__init__.py+5 added-7 removed
14 unmodified lines
15from itsdangerous import json as _json16from jinja2 import Markup17from werkzeug.http import http_date1819from .._compat import PY220from .._compat import text_type19from ..globals import current_app20from ..globals import request2122try:23 import dataclasses24except ImportError:25 # Python < 3.726 dataclasses = None2728# Figure out if simplejson escapes slashes. This behavior was changed29# from one version to another without reason.
64 unmodified lines
94 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)100101102class JSONDecoder(_json.JSONDecoder):
104 unmodified lines
207 """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 rv214215
38 unmodified lines
254255def 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)260261262def htmlsafe_dumps(obj, **kwargs):
34 unmodified lines
297298299def 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)))302303304def jsonify(*args, **kwargs):305 """This function wraps :func:`dumps` to add a few enhancements that make
69 unmodified lines
modified:src/flask/json/tag.py+2 added-4 removed
48 unmodified lines
49from jinja2 import Markup50from werkzeug.http import http_date51from werkzeug.http import parse_date5253from .._compat import iteritems54from .._compat import text_type53from ..json import dumps54from ..json import loads5556
64 unmodified lines
121122 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())126127 tag = to_json128129
48 unmodified lines
178 def check(self, value):179 return callable(getattr(value, "__html__", None))180181 def to_json(self, value):184 return text_type(value.__html__())182 return str(value.__html__())183184 def to_python(self, value):185 return Markup(value)186
121 unmodified lines
deleted:src/flask/_compat.py-115 removed
1# -*- coding: utf-8 -*-2"""3 flask._compat4 ~~~~~~~~~~~~~56 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.910 :copyright: 2010 Pallets11 :license: BSD-3-Clause12"""13import sys1415PY2 = sys.version_info[0] == 216_identity = lambda x: x1718try: # Python 219 text_type = unicode20 string_types = (str, unicode)21 integer_types = (int, long)22except NameError: # Python 323 text_type = str24 string_types = (str,)25 integer_types = (int,)2627if not PY2:28 iterkeys = lambda d: iter(d.keys())29 itervalues = lambda d: iter(d.values())30 iteritems = lambda d: iter(d.items())3132 from inspect import getfullargspec as getargspec33 from io import StringIO34 import collections.abc as collections_abc3536 def reraise(tp, value, tb=None):37 if value.__traceback__ is not tb:38 raise value.with_traceback(tb)39 raise value4041 implements_to_string = _identity4243else:44 iterkeys = lambda d: d.iterkeys()45 itervalues = lambda d: d.itervalues()46 iteritems = lambda d: d.iteritems()4748 from inspect import getargspec49 from cStringIO import StringIO50 import collections as collections_abc5152 exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")5354 def implements_to_string(cls):55 cls.__unicode__ = cls.__str__56 cls.__str__ = lambda x: x.__unicode__().encode("utf-8")57 return cls585960def 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)6869 return type.__new__(metaclass, "temporary_class", (), {})707172# 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.83BROKEN_PYPY_CTXMGR_EXIT = False84if hasattr(sys, "pypy_version_info"):8586 class _Mgr(object):87 def __enter__(self):88 return self8990 def __exit__(self, *args):91 if hasattr(sys, "exc_clear"):92 # Python 3 (PyPy3) doesn't have exc_clear93 sys.exc_clear()9495 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 pass107108109try:110 from os import fspath111except 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 path
modified:src/flask/app.py+29 added-41 removed
29 unmodified lines
30from werkzeug.wrappers import BaseResponse3132from . import cli33from . import json34from ._compat import integer_types35from ._compat import reraise36from ._compat import string_types37from ._compat import text_type34from .config import Config35from .config import ConfigAttribute36from .ctx import _AppCtxGlobals37from .ctx import AppContext
1136 unmodified lines
1174 # 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)11841185 # Methods that should always be added
87 unmodified lines
12731274 :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 lines
1722 message.17231724 .. 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.17361726 if isinstance(e, BadRequestKeyError):1727 if self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]:1728 e.show_exception = True1729
10 unmodified lines
17401741 handler = self._find_error_handler(e)17421743 if handler is None:1755 reraise(exc_type, exc_value, tb)1744 raise17451746 return handler(e)17471748 def handle_exception(self, e):1749 """Handle an exception that did not have an error handler
28 unmodified lines
1778 even for the default 500 response when there is no handler.17791780 .. 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)17841785 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 raise17901805 self.log_exception((exc_type, exc_value, tb))1791 raise e17921793 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 = e
215 unmodified lines
2013 )20142015 # 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 lines
2027 # 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 lines
2043 )20442045 # 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 lines
2107 for func in funcs:2108 func(endpoint, values)21092110 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 rv21232136 # 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 raise21282129 raise error21302131 def preprocess_request(self):2132 """Called before the request is dispatched. Calls
247 unmodified lines
modified:src/flask/cli.py+5 added-13 removed
23 unmodified lines
2425import click26from werkzeug.utils import import_string2728from ._compat import getargspec29from ._compat import itervalues30from ._compat import reraise31from ._compat import text_type28from .globals import current_app29from .helpers import get_debug_flag30from .helpers import get_env31from .helpers import get_load_dotenv
26 unmodified lines
58 if isinstance(app, Flask):59 return app6061 # 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)]6364 if len(matches) == 1:65 return matches[0]66 elif len(matches) > 1:
33 unmodified lines
100 """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.defaults107108 if "script_info" in arg_names:
127 unmodified lines
236 __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 lines
322 __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_info327328 def _load_unlocked(self):329 __traceback_hide__ = True # noqa: F841330 self._app = rv = self.loader()
405 unmodified lines
736 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)741745 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)749742 if value is not None:743 if is_adhoc:744 raise click.BadParameter(745 'When "--cert" is "adhoc", "--key" is not used.', ctx, param
221 unmodified lines
modified:src/flask/config.py+2 added-5 removed
12 unmodified lines
13import types1415from werkzeug.utils import import_string1617from ._compat import iteritems18from ._compat import string_types172018class ConfigAttribute(object):19 """Makes an attribute forward to the config"""2021 def __init__(self, name, get_converter=None):
143 unmodified lines
165 using :meth:`from_object`.166167 :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 lines
257258 .. 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 lines
modified:src/flask/ctx.py-8 removed
11 unmodified lines
12from functools import update_wrapper1314from werkzeug.exceptions import HTTPException1516from ._compat import BROKEN_PYPY_CTXMGR_EXIT17from ._compat import reraise16from .globals import _app_ctx_stack17from .globals import _request_ctx_stack18from .signals import appcontext_popped19from .signals import appcontext_pushed
225 unmodified lines
245246 def __exit__(self, exc_type, exc_value, tb):247 self.pop(exc_value)248251 if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:252 reraise(exc_type, exc_value, tb)249254250class 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 the
203 unmodified lines
457 # 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)460466 if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:467 reraise(exc_type, exc_value, tb)468461 def __repr__(self):462 return "<%s '%s' [%s] of %s>" % (463 self.__class__.__name__,464 self.request.url,
3 unmodified lines
modified:src/flask/debughelpers.py+2 added-5 removed
9 unmodified lines
10"""11import os12from warnings import warn1314from ._compat import implements_to_string15from ._compat import text_type14from .app import Flask15from .blueprints import Blueprint16from .globals import _request_ctx_stack17
3 unmodified lines
21 unexpected unicode or binary data.22 """232427@implements_to_string25class 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 lines
106 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)119120
60 unmodified lines
modified:src/flask/helpers.py+7 added-21 removed
28 unmodified lines
29from werkzeug.routing import BuildError30from werkzeug.urls import url_quote31from werkzeug.wsgi import wrap_file3233from ._compat import fspath34from ._compat import PY235from ._compat import string_types36from ._compat import text_type33from .globals import _app_ctx_stack34from .globals import _request_ctx_stack35from .globals import current_app36from .globals import request
534 unmodified lines
571 mtime = None572 fsize = None573574 if hasattr(filename_or_fp, "__fspath__"):579 filename_or_fp = fspath(filename_or_fp)575 filename_or_fp = os.fspath(filename_or_fp)576581 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 = None
21 unmodified lines
603 if as_attachment:604 if attachment_filename is None:605 raise TypeError("filename unavailable, required for sending as attachment")606611 if not isinstance(attachment_filename, text_type):607 if not isinstance(attachment_filename, str):608 attachment_filename = attachment_filename.decode("utf-8")609610 try:611 attachment_filename = attachment_filename.encode("ascii")
1 unmodified line
613 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 lines
673 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 lines
764 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 lines
11351136def is_ip(value):1137 """Determine if the given string is an IP address.11381143 Python 2 on Windows doesn't provide ``inet_pton``, so this only1144 checks IPv4 addresses in that environment.11451139 :param value: value to check1140 :type value: str11411142 :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 False11581145 for family in (socket.AF_INET, socket.AF_INET6):1146 try:1147 socket.inet_pton(family, value)1148 except socket.error:
5 unmodified lines
modified:src/flask/sessions.py+2 added-2 removed
8 unmodified lines
9 :license: BSD-3-Clause10"""11import hashlib12import warnings13from collections.abc import MutableMapping14from datetime import datetime1516from itsdangerous import BadSignature17from itsdangerous import URLSafeTimedSerializer18from werkzeug.datastructures import CallbackDict1919from ._compat import collections_abc20from .helpers import is_ip21from .helpers import total_seconds22from .json.tag import TaggedJSONSerializer232425class SessionMixin(collections_abc.MutableMapping):25class SessionMixin(MutableMapping):26 """Expands a basic dictionary with session attributes."""2728 @property29 def permanent(self):
365 unmodified lines
modified:src/flask/views.py+1 added-2 removed
6 unmodified lines
78 :copyright: 2010 Pallets9 :license: BSD-3-Clause10"""11from ._compat import with_metaclass11from .globals import request121314http_method_funcs = frozenset(
118 unmodified lines
133 if methods:134 cls.methods = methods135136138class MethodView(with_metaclass(MethodViewType, View)):137class 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 lines
modified:tests/test_basic.py+1 added-2 removed
22 unmodified lines
23from werkzeug.http import parse_date24from werkzeug.routing import BuildError2526import flask27from flask._compat import text_type272829def test_options_work(app, client):30 @app.route("/", methods=["GET", "POST"])
380 unmodified lines
411 return ""412413 @app.route("/test")414 def test():416 return text_type(flask.session.permanent)415 return str(flask.session.permanent)416417 rv = client.get("/")418 assert "set-cookie" in rv.headers419 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])
1559 unmodified lines
modified:tests/test_blueprints.py+1 added-2 removed
13 unmodified lines
14from jinja2 import TemplateNotFound15from werkzeug.http import parse_cache_control_header1617import flask18from flask._compat import text_type181920def test_blueprint_specific_error_handling(app, client):21 frontend = flask.Blueprint("frontend", __name__)
126 unmodified lines
148 return "%s/%d" % (bar, baz)149150 @bp.route("/bar")151 def bar(bar):153 return text_type(bar)152 return str(bar)153154 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 lines
modified:tests/test_config.py-3 removed
12 unmodified lines
1314import pytest1516import flask17from flask._compat import PY2171819# config keys used for the TestConfig20TEST_KEY = "foo"
175 unmodified lines
196 )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 lines
23from werkzeug.http import parse_options_header2425import flask26from flask import json27from flask._compat import PY228from flask._compat import StringIO29from flask._compat import text_type27from flask.helpers import get_debug_flag28from flask.helpers import get_env2930
81 unmodified lines
112113 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()))117118 rv = client.post("/json", data="malformed", content_type="application/json")119 assert rv.status_code == 400120
15 unmodified lines
136 assert rv == expected137138 def test_json_dump_to_file(self, app, app_ctx):139 test_data = {"name": "Flask"}143 out = StringIO()140 out = io.StringIO()141142 flask.json.dump(test_data, out)143 out.seek(0)144 rv = flask.json.load(out)
105 unmodified lines
250 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"])255256 rv = client.post(257 "/add",258 data=flask.json.dumps({"a": 1, "b": 2}),
4 unmodified lines
263 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 lines
443 except AssertionError:444 assert lines == sorted_by_str445446450class PyStringIO(object):447class PyBytesIO(object):448 def __init__(self, *args, **kwargs):449 self._io = io.BytesIO(*args, **kwargs)450451 def __getattr__(self, name):
47 unmodified lines
499 "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 lines
517 @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 lines
modified:tests/test_instance_config.py-17 removed
10 unmodified lines
1112import pytest1314import flask15from flask._compat import PY2151617def test_explicit_instance_paths(modules_tmpdir):18 with pytest.raises(ValueError) as excinfo:
107 unmodified lines
126 )127 finally:128 if "site_egg" in sys.modules:129 del sys.modules["site_egg"]131132133@pytest.mark.skipif(not PY2, reason="This only works under Python 2.")134def 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__)")137138 class Loader(object):139 def find_module(self, name, path=None):140 return self141142 sys.meta_path.append(Loader())143 request.addfinalizer(sys.meta_path.pop)144145 with pytest.raises(AttributeError):146 import unimportable # noqa: F401
modified:tests/test_logging.py+1 added-1 removed
6 unmodified lines
7:license: BSD-3-Clause8"""9import logging10import sys11from io import StringIO1213import pytest1414from flask._compat import StringIO15from flask.logging import default_handler16from flask.logging import has_level_handler17from flask.logging import wsgi_errors_stream18
88 unmodified lines
deleted:tests/test_meta.py-6 removed
1import io234def 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 lines
89 :copyright: 2010 Pallets10 :license: BSD-3-Clause11"""12from io import StringIO1314import flask13from flask._compat import StringIO151617def test_suppressed_exception_logging():18 class SuppressedFlask(flask.Flask):
14 unmodified lines
modified:tests/test_testing.py+1 added-2 removed
12 unmodified lines
13import werkzeug1415import flask16from flask import appcontext_popped17from flask._compat import text_type17from flask.cli import ScriptInfo18from flask.json import jsonify19from flask.testing import EnvironBuilder20from flask.testing import FlaskCliRunner
161 unmodified lines
182183def test_session_transactions(app, client):184 @app.route("/")185 def index():187 return text_type(flask.session["foo"])186 return str(flask.session["foo"])187188 with client:189 with client.session_transaction() as sess:190 assert len(sess) == 0
246 unmodified lines