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
Provenance
- Commit
b46f594- Tree
5953b83- Author
Jon S. Stumpf <jon.stumpf@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
549fed2
23 files changed+86 added−89 removed
modified:docs/testing.rst+1 added-1 removed
52 unmodified lines53 @pytest.fixture54 def client():55 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()56 flaskr.app.config['TESTING'] = True57- 57+58 with flaskr.app.test_client() as client:59 with flaskr.app.app_context():60 flaskr.init_db()61 yield client398 unmodified linesmodified:flask/_compat.py+2 added-2 removed
62 unmodified lines63 # 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)69 70 return type.__new__(metaclass, "temporary_class", (), {})71 24 unmodified lines96 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 linesmodified:flask/app.py+2 added-2 removed
1959 unmodified lines1960 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 rv429 unmodified lines2398 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 linesmodified:flask/cli.py+7 added-7 removed
228 unmodified lines229 return ".".join(module_name[::-1])230 231 232 def locate_app(script_info, module_name, app_name, raise_if_not_found=True):233- __traceback_hide__ = True233+ __traceback_hide__ = True # noqa: F841234 235 try:236 __import__(module_name)237 except ImportError:63 unmodified lines301 self._load_in_background()302 303 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 lines312 t = Thread(target=_load_app, args=())313 t.start()314 315 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)321 322 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 rv327 328 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 lines363 """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: F841368 369 if self._loaded_app is not None:370 return self._loaded_app371 329 unmodified lines701 value = click.STRING(value, param, ctx).lower()702 703 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 linesmodified:flask/helpers.py+2 added-2 removed
228 unmodified lines229 url_for('.index')230 231 For more information, head over to the :ref:`Quickstart <url-building>`.232 233- 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.235 236 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 lines417 current_app._get_current_object(), message=message, category=category418 )419 420 421-def get_flashed_messages(with_categories=False, category_filter=[]):421+def 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 will690 unmodified linesmodified:flask/templating.py+1 added-1 removed
76 unmodified lines77 return trv78 raise TemplateNotFound(template)79 80 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 continue67 unmodified linesmodified:flask/testing.py+1 added-1 removed
14 unmodified lines15 from contextlib import contextmanager16 17 from click.testing import CliRunner18 from flask.cli import ScriptInfo19-from werkzeug.test import Client, EnvironBuilder19+from werkzeug.test import Client20 from flask import _request_ctx_stack21 from flask.json import dumps as json_dumps22 from werkzeug.urls import url_parse23 260 unmodified linesmodified:flask/wrappers.py+2 added-1 removed
43 unmodified lines44 #: 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 = None84 unmodified linesmodified:scripts/make-release.py+1 added-1 removed
12 unmodified lines13 def 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())18 19 if match is None:20 continue21 141 unmodified linesmodified:tests/test_apps/helloworld/wsgi.py+1 added-1 removed
1-from hello import app1+from hello import app # noqa: F401modified:tests/test_basic.py+15 added-12 removed
161 unmodified lines162 163 app.add_url_rule("/", "index", index)164 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])165 166- # 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"])169 170 assert client.get("/").data == b"GET"171 rv = client.post("/")607 unmodified lines779 # test that all teardown_requests get passed the same original780 # exception.781 try:782 raise TypeError()782- except:783+ except Exception:784 pass785 786 @app.teardown_request787 def teardown_request2(exc):3 unmodified lines791 # test that all teardown_requests get passed the same original792 # exception.793 try:794 raise TypeError()794- except:795+ except Exception:796 pass797 798 @app.route("/")799 def fails():163 unmodified lines963 assert isinstance(e, ForbiddenSubclass)964 return "banana"965 966 @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 lines1065 app.testing = False1066 1067 @app.before_request1068 def before_request():1068- if trigger == "before":1069+ if _trigger == "before":1070 1 // 01071 1072 @app.after_request1073 def after_request(response):1073- if trigger == "after":1074+ if _trigger == "after":1075 1 // 01076 return response1077 1078 @app.route("/")3 unmodified lines1082 @app.errorhandler(500)1083 def internal_server_error(e):1084 return "Hello Server Error", 5001085 1085- 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 lines1459 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)1470 1471 1472 def test_request_locals():103 unmodified lines1576 1577 @app.before_request1578 def always_first():1579 flask.request.form["myfile"]1577- assert False1580+ AssertionError()1581 1582 @app.route("/accept", methods=["POST"])1583 def accept_file():1584 flask.request.form["myfile"]1582- assert False1585+ AssertionError()1586 1587 @app.errorhandler(413)1588 def catcher(error):1589 return "42"177 unmodified lines1767 @app.route("/fail")1768 def fail_func():1769 1 // 01770 1768- for x in range(3):1771+ for _x in range(3):1772 with pytest.raises(ZeroDivisionError):1773 client.get("/fail")1774 1775 assert flask._request_ctx_stack.top is not None225 unmodified linesmodified:tests/test_blueprints.py+1 added-1 removed
703 unmodified lines704 705 def test_context_processing(app, client):706 answer_bp = flask.Blueprint("answer_bp", __name__)707 708- 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 linesmodified:tests/test_cli.py+1 added-1 removed
54 unmodified lines55 assert testapp.cli.name == testapp.name56 57 58 def 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()61 62 class Module:63 app = Flask("appname")606 unmodified linesmodified:tests/test_config.py+22 added-29 removed
74 unmodified lines75 app.config.from_object(Test)76 common_object_test(app)77 78 79-def 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")79+def 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)86 89- 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)92 93 96-def 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 = env94+def 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)105 106 107 def test_config_missing():108 app = flask.Flask(__name__)94 unmodified linesmodified:tests/test_helpers.py+11 added-11 removed
180 unmodified lines181 assert flask.json.loads(rv.data) == d182 183 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 lines195 ]196 197 @app.route("/args_unpack")198 def return_args_unpack():199- return flask.jsonify(*l)199+ return flask.jsonify(*a_list)200 201 @app.route("/array")202 def return_array():203- return flask.jsonify(l)203+ return flask.jsonify(a_list)204 205 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_list209 210 def test_jsonify_date_types(self, app, client):211 """Test jsonify with datetime.date and datetime.datetime types."""212 test_dates = (64 unmodified lines277 )278 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'279 280 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 = val284 285 class MyEncoder(flask.json.JSONEncoder):26 unmodified lines312 )313 assert rv.data == b'"<42>"'314 315 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 = val319 320 class MyEncoder(flask.json.JSONEncoder):30 unmodified lines351 content_type="application/json",352 )353 assert rv.data == b'"<42>"'354 355+ @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 lines369 rv = client.get(u"/?foo=정상처리".encode("euc-kr"))370 assert rv.status_code == 200371 assert rv.data == u"정상처리".encode("utf-8")372 370- if not has_encoding("euc-kr"):371- test_modified_url_encoding = None372-373 def test_json_key_sorting(self, app, client):374 app.debug = True375 376- assert app.config["JSON_SORT_KEYS"] == True376+ assert app.config["JSON_SORT_KEYS"]377 d = dict.fromkeys(range(20), "foo")378 379 @app.route("/")380 def index():476 unmodified lines857 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.")862 863 864 class TestStreaming(object):865 def test_streaming_with_context(self, app, client):173 unmodified linesmodified:tests/test_instance_config.py+1 added-1 removed
138 unmodified lines139 sys.meta_path.append(Loader())140 request.addfinalizer(sys.meta_path.pop)141 142 with pytest.raises(AttributeError):143- import unimportable143+ import unimportable # noqa: F401modified:tests/test_json_tag.py+1 added-1 removed
46 unmodified lines47 assert isinstance(s.order[0], TagDict)48 49 50 def test_custom_tag():51- class Foo(object):51+ class Foo(object): # noqa: B903, for Python2 compatibility52 def __init__(self, data):53 self.data = data54 55 class TagFoo(JSONTag):38 unmodified linesmodified:tests/test_regression.py+1 added-1 removed
62 unmodified lines63 64 # 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()69 70 71 def test_safe_join_toplevel_pardir():27 unmodified linesmodified:tests/test_reqctx.py+1 added-2 removed
189 unmodified lines190 191 @app.route("/")192 def index():193 flask.session["fizz"] = "buzz"194- reqctx = flask._request_ctx_stack.top.copy()194 195 @flask.copy_current_request_context196 def g():197 assert flask.request28 unmodified lines226 227 @app.route("/")228 def index():229 # shouldn't get here231- assert False230+ AssertionError()231 232 response = app.test_client().get("/")233 assert response.status_code == 500234 assert not flask.request57 unmodified linesmodified:tests/test_templating.py+5 added-5 removed
396 unmodified lines397 398 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)399 400 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_reload403 404 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_reload407 408 409 def test_template_loader_debugging(test_apps, monkeypatch):410 from blueprintapp import app411 412 called = []413 414 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 linesmodified:tests/test_testing.py+3 added-3 removed
209 unmodified lines210 app.testing = True211 212 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)217 218 219 def 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 line226 227 def 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)233 234 210 unmodified linesmodified:tests/test_user_error_handler.py+3 added-3 removed
147 unmodified lines148 assert isinstance(e, NotFound)149 return "bp-default"150 151 @bp.errorhandler(Forbidden)152- def bp_exception_handler(e):152+ def bp_forbidden_handler(e):153 assert isinstance(e, Forbidden)154 return "bp-forbidden"155 156 @bp.route("/undefined")6 unmodified lines163 164 app = flask.Flask(__name__)165 166 @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"171 172 @app.errorhandler(Forbidden)173- def catchall_errorhandler(e):173+ def catchall_forbidden_handler(e):174 assert isinstance(e, Forbidden)175 return "forbidden"176 177 @app.route("/forbidden")16 unmodified linesmodified:setup.cfg+1 added
44 unmodified lines45 max-line-length = 8046 per-file-ignores =47 # __init__ modules export names48 **/__init__.py: F40149+ **/_compat.py: E731, B301, F401