Skip to content
Myr

address flake8 issues

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Jon S. Stumpf · committed by David Lord · parent 549fed2 · Browse files · 23 files+86 added−89 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

23 files+86 added−89 removed

  • tests:+66 added−71 removed
  • other:+20 added−18 removed

23 files+86 added−89 removed

modified:docs/testing.rst+1 added-1 removed
52 unmodified lines
53 @pytest.fixture54 def client():55 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()56 flaskr.app.config['TESTING'] = True57 5758 with flaskr.app.test_client() as client:59 with flaskr.app.app_context():60 flaskr.init_db()61 yield client
398 unmodified lines
modified:flask/_compat.py+2 added-2 removed
62 unmodified lines
63 # This requires a bit of explanation: the basic idea is to make a64 # dummy metaclass for one level of class instantiation that replaces65 # itself with the actual metaclass.66 class metaclass(type):67 def __new__(cls, name, this_bases, d):67 def __new__(mcs, name, this_bases, d):68 return meta(name, bases, d)6970 return type.__new__(metaclass, "temporary_class", (), {})71
24 unmodified lines
96 try:97 try:98 with _Mgr():99 raise AssertionError()100 except:100 except: # noqa: B001101 # We intentionally use a bare except here. See the comment above102 # regarding a pypy bug as to why.103 raise104 except TypeError:
12 unmodified lines
modified:flask/app.py+2 added-2 removed
1959 unmodified lines
1960 try:1961 adapter.match(method="--")1962 except MethodNotAllowed as e:1963 methods = e.valid_methods1964 except HTTPException as e:1964 except HTTPException:1965 pass1966 rv = self.response_class()1967 rv.allow.update(methods)1968 return rv
429 unmodified lines
2398 response = self.full_dispatch_request()2399 except Exception as e:2400 error = e2401 response = self.handle_exception(e)2402 except:2402 except: # noqa: B0012403 error = sys.exc_info()[1]2404 raise2405 return response(environ, start_response)2406 finally:
12 unmodified lines
modified:flask/cli.py+7 added-7 removed
228 unmodified lines
229 return ".".join(module_name[::-1])230231232def locate_app(script_info, module_name, app_name, raise_if_not_found=True):233 __traceback_hide__ = True233 __traceback_hide__ = True # noqa: F841234235 try:236 __import__(module_name)237 except ImportError:
63 unmodified lines
301 self._load_in_background()302303 def _load_in_background(self):304 def _load_app():305 __traceback_hide__ = True305 __traceback_hide__ = True # noqa: F841306 with self._lock:307 try:308 self._load_unlocked()309 except Exception:
2 unmodified lines
312 t = Thread(target=_load_app, args=())313 t.start()314315 def _flush_bg_loading_exception(self):316 __traceback_hide__ = True316 __traceback_hide__ = True # noqa: F841317 exc_info = self._bg_loading_exc_info318 if exc_info is not None:319 self._bg_loading_exc_info = None320 reraise(*exc_info)321322 def _load_unlocked(self):323 __traceback_hide__ = True323 __traceback_hide__ = True # noqa: F841324 self._app = rv = self.loader()325 self._bg_loading_exc_info = None326 return rv327328 def __call__(self, environ, start_response):329 __traceback_hide__ = True329 __traceback_hide__ = True # noqa: F841330 if self._app is not None:331 return self._app(environ, start_response)332 self._flush_bg_loading_exception()333 with self._lock:
29 unmodified lines
363 """Loads the Flask app (if not yet loaded) and returns it. Calling364 this multiple times will just result in the already loaded app to365 be returned.366 """367 __traceback_hide__ = True367 __traceback_hide__ = True # noqa: F841368369 if self._loaded_app is not None:370 return self._loaded_app371
329 unmodified lines
701 value = click.STRING(value, param, ctx).lower()702703 if value == "adhoc":704 try:705 import OpenSSL705 import OpenSSL # noqa: F401706 except ImportError:707 raise click.BadParameter(708 "Using ad-hoc certificates requires pyOpenSSL.", ctx, param709 )
254 unmodified lines
modified:flask/helpers.py+2 added-2 removed
228 unmodified lines
229 url_for('.index')230231 For more information, head over to the :ref:`Quickstart <url-building>`.232233 Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when 233 Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when234 generating URLs outside of a request context.235236 To integrate applications, :class:`Flask` has a hook to intercept URL build237 errors through :attr:`Flask.url_build_error_handlers`. The `url_for`
179 unmodified lines
417 current_app._get_current_object(), message=message, category=category418 )419420421def get_flashed_messages(with_categories=False, category_filter=[]):421def get_flashed_messages(with_categories=False, category_filter=()):422 """Pulls all flashed messages from the session and returns them.423 Further calls in the same request to the function will return424 the same messages. By default just the messages are returned,425 but when `with_categories` is set to ``True``, the return value will
690 unmodified lines
modified:flask/templating.py+1 added-1 removed
76 unmodified lines
77 return trv78 raise TemplateNotFound(template)7980 def _get_source_fast(self, environment, template):81 for srcobj, loader in self._iter_loaders(template):81 for _srcobj, loader in self._iter_loaders(template):82 try:83 return loader.get_source(environment, template)84 except TemplateNotFound:85 continue
67 unmodified lines
modified:flask/testing.py+1 added-1 removed
14 unmodified lines
15from contextlib import contextmanager1617from click.testing import CliRunner18from flask.cli import ScriptInfo19from werkzeug.test import Client, EnvironBuilder19from werkzeug.test import Client20from flask import _request_ctx_stack21from flask.json import dumps as json_dumps22from werkzeug.urls import url_parse23
260 unmodified lines
modified:flask/wrappers.py+2 added-1 removed
43 unmodified lines
44 #: useful to inspect which methods are allowed for the URL from45 #: a before/after handler (``request.url_rule.methods``) etc.46 #: Though if the request's method was invalid for the URL rule,47 #: the valid list is available in ``routing_exception.valid_methods``48 #: instead (an attribute of the Werkzeug exception :exc:`~werkzeug.exceptions.MethodNotAllowed`)48 #: instead (an attribute of the Werkzeug exception49 #: :exc:`~werkzeug.exceptions.MethodNotAllowed`)50 #: because the request was never internally bound.51 #:52 #: .. versionadded:: 0.653 url_rule = None
84 unmodified lines
modified:scripts/make-release.py+1 added-1 removed
12 unmodified lines
13def parse_changelog():14 with open("CHANGES.rst") as f:15 lineiter = iter(f)16 for line in lineiter:17 match = re.search("^Version\s+(.*)", line.strip())17 match = re.search(r"^Version\s+(.*)", line.strip())1819 if match is None:20 continue21
141 unmodified lines
modified:tests/test_apps/helloworld/wsgi.py+1 added-1 removed
1from hello import app1from hello import app # noqa: F401
modified:tests/test_basic.py+15 added-12 removed
161 unmodified lines
162163 app.add_url_rule("/", "index", index)164 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])165166 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods166 # Issue 1288: Test that automatic options are not added167 # when non-uppercase 'options' in methods168 app.add_url_rule("/options", "options", options, methods=["options"])169170 assert client.get("/").data == b"GET"171 rv = client.post("/")
607 unmodified lines
779 # test that all teardown_requests get passed the same original780 # exception.781 try:782 raise TypeError()782 except:783 except Exception:784 pass785786 @app.teardown_request787 def teardown_request2(exc):
3 unmodified lines
791 # test that all teardown_requests get passed the same original792 # exception.793 try:794 raise TypeError()794 except:795 except Exception:796 pass797798 @app.route("/")799 def fails():
163 unmodified lines
963 assert isinstance(e, ForbiddenSubclass)964 return "banana"965966 @app.errorhandler(403)966 def handle_forbidden_subclass(e):967 def handle_403(e):968 assert not isinstance(e, ForbiddenSubclass)969 assert isinstance(e, Forbidden)970 return "apple"971
93 unmodified lines
1065 app.testing = False10661067 @app.before_request1068 def before_request():1068 if trigger == "before":1069 if _trigger == "before":1070 1 // 010711072 @app.after_request1073 def after_request(response):1073 if trigger == "after":1074 if _trigger == "after":1075 1 // 01076 return response10771078 @app.route("/")
3 unmodified lines
1082 @app.errorhandler(500)1083 def internal_server_error(e):1084 return "Hello Server Error", 50010851085 for trigger in "before", "after":1086 for _trigger in "before", "after":1087 rv = client.get("/")1088 assert rv.status_code == 5001089 assert rv.data == b"Hello Server Error"1090
368 unmodified lines
1459 assert rv == "http://example.com/static/index.html"1460 # Providing static_host without host_matching=True should error.1461 with pytest.raises(Exception):1462 flask.Flask(__name__, static_host="example.com")1462 # Providing host_matching=True with static_folder but without static_host should error.1463 # Providing host_matching=True with static_folder1464 # but without static_host should error.1465 with pytest.raises(Exception):1466 flask.Flask(__name__, host_matching=True)1465 # Providing host_matching=True without static_host but with static_folder=None should not error.1467 # Providing host_matching=True without static_host1468 # but with static_folder=None should not error.1469 flask.Flask(__name__, host_matching=True, static_folder=None)147014711472def test_request_locals():
103 unmodified lines
15761577 @app.before_request1578 def always_first():1579 flask.request.form["myfile"]1577 assert False1580 AssertionError()15811582 @app.route("/accept", methods=["POST"])1583 def accept_file():1584 flask.request.form["myfile"]1582 assert False1585 AssertionError()15861587 @app.errorhandler(413)1588 def catcher(error):1589 return "42"
177 unmodified lines
1767 @app.route("/fail")1768 def fail_func():1769 1 // 017701768 for x in range(3):1771 for _x in range(3):1772 with pytest.raises(ZeroDivisionError):1773 client.get("/fail")17741775 assert flask._request_ctx_stack.top is not None
225 unmodified lines
modified:tests/test_blueprints.py+1 added-1 removed
703 unmodified lines
704705def test_context_processing(app, client):706 answer_bp = flask.Blueprint("answer_bp", __name__)707708 template_string = lambda: flask.render_template_string(708 template_string = lambda: flask.render_template_string( # noqa: E731709 "{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}"710 "{% if answer %}{{ answer }} is the answer.{% endif %}"711 )712
152 unmodified lines
modified:tests/test_cli.py+1 added-1 removed
54 unmodified lines
55 assert testapp.cli.name == testapp.name565758def test_find_best_app(test_apps):59 """Test if `find_best_app` behaves as expected with different combinations of input."""59 """Test if `find_best_app` behaves as expected with different combinations of input.""" # noqa: B95060 script_info = ScriptInfo()6162 class Module:63 app = Flask("appname")
606 unmodified lines
modified:tests/test_config.py+22 added-29 removed
74 unmodified lines
75 app.config.from_object(Test)76 common_object_test(app)777879def test_config_from_envvar():80 env = os.environ81 try:82 os.environ = {}83 app = flask.Flask(__name__)84 with pytest.raises(RuntimeError) as e:85 app.config.from_envvar("FOO_SETTINGS")79def test_config_from_envvar(monkeypatch):80 monkeypatch.setattr("os.environ", {})81 app = flask.Flask(__name__)82 with pytest.raises(RuntimeError) as e:83 app.config.from_envvar("FOO_SETTINGS")84 assert "'FOO_SETTINGS' is not set" in str(e.value)87 assert not app.config.from_envvar("FOO_SETTINGS", silent=True)85 assert not app.config.from_envvar("FOO_SETTINGS", silent=True)8689 os.environ = {"FOO_SETTINGS": __file__.rsplit(".", 1)[0] + ".py"}90 assert app.config.from_envvar("FOO_SETTINGS")91 common_object_test(app)92 finally:93 os.environ = env87 monkeypatch.setattr(88 "os.environ", {"FOO_SETTINGS": __file__.rsplit(".", 1)[0] + ".py"}89 )90 assert app.config.from_envvar("FOO_SETTINGS")91 common_object_test(app)929396def test_config_from_envvar_missing():97 env = os.environ98 try:99 os.environ = {"FOO_SETTINGS": "missing.cfg"}100 with pytest.raises(IOError) as e:101 app = flask.Flask(__name__)102 app.config.from_envvar("FOO_SETTINGS")103 msg = str(e.value)104 assert msg.startswith(105 "[Errno 2] Unable to load configuration "106 "file (No such file or directory):"107 )108 assert msg.endswith("missing.cfg'")109 assert not app.config.from_envvar("FOO_SETTINGS", silent=True)110 finally:111 os.environ = env94def test_config_from_envvar_missing(monkeypatch):95 monkeypatch.setattr("os.environ", {"FOO_SETTINGS": "missing.cfg"})96 with pytest.raises(IOError) as e:97 app = flask.Flask(__name__)98 app.config.from_envvar("FOO_SETTINGS")99 msg = str(e.value)100 assert msg.startswith(101 "[Errno 2] Unable to load configuration " "file (No such file or directory):"102 )103 assert msg.endswith("missing.cfg'")104 assert not app.config.from_envvar("FOO_SETTINGS", silent=True)105106107def test_config_missing():108 app = flask.Flask(__name__)
94 unmodified lines
modified:tests/test_helpers.py+11 added-11 removed
180 unmodified lines
181 assert flask.json.loads(rv.data) == d182183 def test_jsonify_arrays(self, app, client):184 """Test jsonify of lists and args unpacking."""185 l = [185 a_list = [186 0,187 42,188 3.14,189 "t",
5 unmodified lines
195 ]196197 @app.route("/args_unpack")198 def return_args_unpack():199 return flask.jsonify(*l)199 return flask.jsonify(*a_list)200201 @app.route("/array")202 def return_array():203 return flask.jsonify(l)203 return flask.jsonify(a_list)204205 for url in "/args_unpack", "/array":206 rv = client.get(url)207 assert rv.mimetype == "application/json"208 assert flask.json.loads(rv.data) == l208 assert flask.json.loads(rv.data) == a_list209210 def test_jsonify_date_types(self, app, client):211 """Test jsonify with datetime.date and datetime.datetime types."""212 test_dates = (
64 unmodified lines
277 )278 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'279280 def test_json_customization(self, app, client):281 class X(object):281 class X(object): # noqa: B903, for Python2 compatibility282 def __init__(self, val):283 self.val = val284285 class MyEncoder(flask.json.JSONEncoder):
26 unmodified lines
312 )313 assert rv.data == b'"<42>"'314315 def test_blueprint_json_customization(self, app, client):316 class X(object):316 class X(object): # noqa: B903, for Python2 compatibility317 def __init__(self, val):318 self.val = val319320 class MyEncoder(flask.json.JSONEncoder):
30 unmodified lines
351 content_type="application/json",352 )353 assert rv.data == b'"<42>"'354355 @pytest.mark.skipif(356 not has_encoding("euc-kr"), reason="The euc-kr encoding is required."357 )358 def test_modified_url_encoding(self, app, client):359 class ModifiedRequest(flask.Request):360 url_charset = "euc-kr"361
7 unmodified lines
369 rv = client.get(u"/?foo=정상처리".encode("euc-kr"))370 assert rv.status_code == 200371 assert rv.data == u"정상처리".encode("utf-8")372370 if not has_encoding("euc-kr"):371 test_modified_url_encoding = None372373 def test_json_key_sorting(self, app, client):374 app.debug = True375376 assert app.config["JSON_SORT_KEYS"] == True376 assert app.config["JSON_SORT_KEYS"]377 d = dict.fromkeys(range(20), "foo")378379 @app.route("/")380 def index():
476 unmodified lines
857 modules_tmpdir.join("importerror.py").write("raise NotImplementedError()")858 try:859 flask.Flask("importerror")860 except NotImplementedError:861 assert False, "Flask(import_name) is importing import_name."861 AssertionError("Flask(import_name) is importing import_name.")862863864class TestStreaming(object):865 def test_streaming_with_context(self, app, client):
173 unmodified lines
modified:tests/test_instance_config.py+1 added-1 removed
138 unmodified lines
139 sys.meta_path.append(Loader())140 request.addfinalizer(sys.meta_path.pop)141142 with pytest.raises(AttributeError):143 import unimportable143 import unimportable # noqa: F401
modified:tests/test_json_tag.py+1 added-1 removed
46 unmodified lines
47 assert isinstance(s.order[0], TagDict)484950def test_custom_tag():51 class Foo(object):51 class Foo(object): # noqa: B903, for Python2 compatibility52 def __init__(self, data):53 self.data = data5455 class TagFoo(JSONTag):
38 unmodified lines
modified:tests/test_regression.py+1 added-1 removed
62 unmodified lines
6364 # This test only works on CPython 2.7.65 if sys.version_info >= (2, 7) and not hasattr(sys, "pypy_translation_info"):66 with assert_no_leak():67 for x in range(10):67 for _x in range(10):68 fire()697071def test_safe_join_toplevel_pardir():
27 unmodified lines
modified:tests/test_reqctx.py+1 added-2 removed
189 unmodified lines
190191 @app.route("/")192 def index():193 flask.session["fizz"] = "buzz"194 reqctx = flask._request_ctx_stack.top.copy()194195 @flask.copy_current_request_context196 def g():197 assert flask.request
28 unmodified lines
226227 @app.route("/")228 def index():229 # shouldn't get here231 assert False230 AssertionError()231232 response = app.test_client().get("/")233 assert response.status_code == 500234 assert not flask.request
57 unmodified lines
modified:tests/test_templating.py+5 added-5 removed
396 unmodified lines
397398 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)399400 app.run()401 assert app.templates_auto_reload == False402 assert app.jinja_env.auto_reload == False401 assert not app.templates_auto_reload402 assert not app.jinja_env.auto_reload403404 app.run(debug=True)405 assert app.templates_auto_reload == True406 assert app.jinja_env.auto_reload == True405 assert app.templates_auto_reload406 assert app.jinja_env.auto_reload407408409def test_template_loader_debugging(test_apps, monkeypatch):410 from blueprintapp import app411412 called = []413414 class _TestHandler(logging.Handler):415 def handle(x, record):415 def handle(self, record):416 called.append(True)417 text = str(record.msg)418 assert '1: trying loader of application "blueprintapp"' in text419 assert (
32 unmodified lines
modified:tests/test_testing.py+3 added-3 removed
209 unmodified lines
210 app.testing = True211212 with app.test_client() as c:213 with pytest.raises(RuntimeError) as e:214 with c.session_transaction() as sess:214 with c.session_transaction():215 pass216 assert "Session backend did not open a session" in str(e.value)217218219def test_session_transactions_keep_context(app, client, req_ctx):220 rv = client.get("/")220 client.get("/")221 req = flask.request._get_current_object()222 assert req is not None223 with client.session_transaction():224 assert req is flask.request._get_current_object()
1 unmodified line
226227def test_session_transaction_needs_cookies(app):228 c = app.test_client(use_cookies=False)229 with pytest.raises(RuntimeError) as e:230 with c.session_transaction() as s:230 with c.session_transaction():231 pass232 assert "cookies" in str(e.value)233234
210 unmodified lines
modified:tests/test_user_error_handler.py+3 added-3 removed
147 unmodified lines
148 assert isinstance(e, NotFound)149 return "bp-default"150151 @bp.errorhandler(Forbidden)152 def bp_exception_handler(e):152 def bp_forbidden_handler(e):153 assert isinstance(e, Forbidden)154 return "bp-forbidden"155156 @bp.route("/undefined")
6 unmodified lines
163164 app = flask.Flask(__name__)165166 @app.errorhandler(HTTPException)167 def catchall_errorhandler(e):167 def catchall_exception_handler(e):168 assert isinstance(e, HTTPException)169 assert isinstance(e, NotFound)170 return "default"171172 @app.errorhandler(Forbidden)173 def catchall_errorhandler(e):173 def catchall_forbidden_handler(e):174 assert isinstance(e, Forbidden)175 return "forbidden"176177 @app.route("/forbidden")
16 unmodified lines
modified:setup.cfg+1 added
44 unmodified lines
45max-line-length = 8046per-file-ignores =47 # __init__ modules export names48 **/__init__.py: F40149 **/_compat.py: E731, B301, F401