Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

385 lines · 10.0 KiB · Python

Last changed by

merge app and request context (#5812)David Lordbefore adoptionadf3636

History of this file

Take it

The walk stopped after 200 commits: lines older than eeebb5a point at it.

bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc

lines 1–2why, one step back
1import importlib.metadata
2

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 3–8why, one step back
3import click
4import pytest56import flask7from flask import appcontext_popped8from flask.cli import ScriptInfo

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 9why, one step back
9from flask.globals import _cv_app

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 10–41why, one step back
10from flask.json import jsonify
11from flask.testing import EnvironBuilder12from flask.testing import FlaskCliRunner131415def test_environ_defaults_from_config(app, client):16 app.config["SERVER_NAME"] = "example.com:1234"17 app.config["APPLICATION_ROOT"] = "/foo"1819 @app.route("/")20 def index():21 return flask.request.url2223 ctx = app.test_request_context()24 assert ctx.request.url == "http://example.com:1234/foo/"2526 rv = client.get("/")27 assert rv.data == b"http://example.com:1234/foo/"282930def test_environ_defaults(app, client, app_ctx, req_ctx):31 @app.route("/")32 def index():33 return flask.request.url3435 ctx = app.test_request_context()36 assert ctx.request.url == "http://localhost/"37 with client:38 rv = client.get("/")39 assert rv.data == b"http://localhost/"4041

bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc

line 42why, one step back
42def test_environ_base_default(app, client):

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 43–44why, one step back
43 @app.route("/")
44 def index():

bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc

lines 45–47why, one step back
45 flask.g.remote_addr = flask.request.remote_addr
46 flask.g.user_agent = flask.request.user_agent.string47 return ""

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

line 48why, one step back
48

bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc

lines 49–54why, one step back
49 with client:
50 client.get("/")51 assert flask.g.remote_addr == "127.0.0.1"52 assert flask.g.user_agent == (53 f"Werkzeug/{importlib.metadata.version('werkzeug')}"54 )

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 55–56why, one step back
55
56

bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc

line 57why, one step back
57def test_environ_base_modified(app, client):

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 58–59why, one step back
58 @app.route("/")
59 def index():

bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc

lines 60–62why, one step back
60 flask.g.remote_addr = flask.request.remote_addr
61 flask.g.user_agent = flask.request.user_agent.string62 return ""

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

line 63why, one step back
63

bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc

line 64why, one step back
64 client.environ_base["REMOTE_ADDR"] = "192.168.0.22"

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 65–66why, one step back
65 client.environ_base["HTTP_USER_AGENT"] = "Foo"
66

bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc

lines 67–70why, one step back
67 with client:
68 client.get("/")69 assert flask.g.remote_addr == "192.168.0.22"70 assert flask.g.user_agent == "Foo"

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 71–140why, one step back
71
7273def test_client_open_environ(app, client, request):74 @app.route("/index")75 def index():76 return flask.request.remote_addr7778 builder = EnvironBuilder(app, path="/index", method="GET")79 request.addfinalizer(builder.close)8081 rv = client.open(builder)82 assert rv.data == b"127.0.0.1"8384 environ = builder.get_environ()85 client.environ_base["REMOTE_ADDR"] = "127.0.0.2"86 rv = client.open(environ)87 assert rv.data == b"127.0.0.2"888990def test_specify_url_scheme(app, client):91 @app.route("/")92 def index():93 return flask.request.url9495 ctx = app.test_request_context(url_scheme="https")96 assert ctx.request.url == "https://localhost/"9798 rv = client.get("/", url_scheme="https")99 assert rv.data == b"https://localhost/"100101102def test_path_is_url(app):103 eb = EnvironBuilder(app, "https://example.com/")104 assert eb.url_scheme == "https"105 assert eb.host == "example.com"106 assert eb.script_root == ""107 assert eb.path == "/"108109110def test_environbuilder_json_dumps(app):111 """EnvironBuilder.json_dumps() takes settings from the app."""112 app.json.ensure_ascii = False113 eb = EnvironBuilder(app, json="\u20ac")114 assert eb.input_stream.read().decode("utf8") == '"\u20ac"'115116117def test_blueprint_with_subdomain():118 app = flask.Flask(__name__, subdomain_matching=True)119 app.config["SERVER_NAME"] = "example.com:1234"120 app.config["APPLICATION_ROOT"] = "/foo"121 client = app.test_client()122123 bp = flask.Blueprint("company", __name__, subdomain="xxx")124125 @bp.route("/")126 def index():127 return flask.request.url128129 app.register_blueprint(bp)130131 ctx = app.test_request_context("/", subdomain="xxx")132 assert ctx.request.url == "http://xxx.example.com:1234/foo/"133134 with ctx:135 assert ctx.request.blueprint == bp.name136137 rv = client.get("/", subdomain="xxx")138 assert rv.data == b"http://xxx.example.com:1234/foo/"139140

Merge branch 'stable'David Lordbefore adoption3301232

lines 141–142why, one step back
141def test_redirect_session(app, client, app_ctx):
142 @app.route("/redirect")

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

line 143why, one step back
143 def index():

Merge branch 'stable'David Lordbefore adoption3301232

lines 144–145why, one step back
144 flask.session["redirect"] = True
145 return flask.redirect("/target")

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

line 146why, one step back
146

Merge branch 'stable'David Lordbefore adoption3301232

line 147why, one step back
147 @app.route("/target")

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

line 148why, one step back
148 def get_session():

Merge branch 'stable'David Lordbefore adoption3301232

lines 149–150why, one step back
149 flask.session["target"] = True
150 return ""

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 151–152why, one step back
151
152 with client:

Merge branch 'stable'David Lordbefore adoption3301232

lines 153–155why, one step back
153 client.get("/redirect", follow_redirects=True)
154 assert flask.session["redirect"] is True155 assert flask.session["target"] is True

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 156–194why, one step back
156
157158def test_session_transactions(app, client):159 @app.route("/")160 def index():161 return str(flask.session["foo"])162163 with client:164 with client.session_transaction() as sess:165 assert len(sess) == 0166 sess["foo"] = [42]167 assert len(sess) == 1168 rv = client.get("/")169 assert rv.data == b"[42]"170 with client.session_transaction() as sess:171 assert len(sess) == 1172 assert sess["foo"] == [42]173174175def test_session_transactions_no_null_sessions():176 app = flask.Flask(__name__)177178 with app.test_client() as c:179 with pytest.raises(RuntimeError) as e:180 with c.session_transaction():181 pass182 assert "Session backend did not open a session" in str(e.value)183184185def test_session_transactions_keep_context(app, client, req_ctx):186 client.get("/")187 req = flask.request._get_current_object()188 assert req is not None189 with client.session_transaction():190 assert req is flask.request._get_current_object()191192193def test_session_transaction_needs_cookies(app):194 c = app.test_client(use_cookies=False)

Merge branch '2.2.x'David Lordbefore adoptionfa0ceb6

lines 195–196why, one step back
195
196 with pytest.raises(TypeError, match="Cookies are disabled."):

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 197–210why, one step back
197 with c.session_transaction():
198 pass199200201def test_test_client_context_binding(app, client):202 app.testing = False203204 @app.route("/")205 def index():206 flask.g.value = 42207 return "Hello World!"208209 @app.route("/other")210 def other():

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

line 211why, one step back
211 raise ZeroDivisionError

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 212–218why, one step back
212
213 with client:214 resp = client.get("/")215 assert flask.g.value == 42216 assert resp.data == b"Hello World!"217 assert resp.status_code == 200218

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

line 219why, one step back
219 with client:

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 220–225why, one step back
220 resp = client.get("/other")
221 assert not hasattr(flask.g, "value")222 assert b"Internal Server Error" in resp.data223 assert resp.status_code == 500224 flask.g.value = 23225

use ruff linter and formatter (#5331)David Lordbefore adoption9a12f34

lines 226–227why, one step back
226 with pytest.raises(RuntimeError):
227 flask.g.value # noqa: B018

Merge branch '2.2.x'David Lordbefore adoptioneeebb5a

lines 228–384why, one step back
228
229230def test_reuse_client(client):231 c = client232233 with c:234 assert client.get("/").status_code == 404235236 with c:237 assert client.get("/").status_code == 404238239240def test_full_url_request(app, client):241 @app.route("/action", methods=["POST"])242 def action():243 return "x"244245 with client:246 rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})247 assert rv.status_code == 200248 assert "gin" in flask.request.form249 assert "vodka" in flask.request.args250251252def test_json_request_and_response(app, client):253 @app.route("/echo", methods=["POST"])254 def echo():255 return jsonify(flask.request.get_json())256257 with client:258 json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}259 rv = client.post("/echo", json=json_data)260261 # Request should be in JSON262 assert flask.request.is_json263 assert flask.request.get_json() == json_data264265 # Response should be in JSON266 assert rv.status_code == 200267 assert rv.is_json268 assert rv.get_json() == json_data269270271def test_client_json_no_app_context(app, client):272 @app.route("/hello", methods=["POST"])273 def hello():274 return f"Hello, {flask.request.json['name']}!"275276 class Namespace:277 count = 0278279 def add(self, app):280 self.count += 1281282 ns = Namespace()283284 with appcontext_popped.connected_to(ns.add, app):285 rv = client.post("/hello", json={"name": "Flask"})286287 assert rv.get_data(as_text=True) == "Hello, Flask!"288 assert ns.count == 1289290291def test_subdomain():292 app = flask.Flask(__name__, subdomain_matching=True)293 app.config["SERVER_NAME"] = "example.com"294 client = app.test_client()295296 @app.route("/", subdomain="<company_id>")297 def view(company_id):298 return company_id299300 with app.test_request_context():301 url = flask.url_for("view", company_id="xxx")302303 with client:304 response = client.get(url)305306 assert 200 == response.status_code307 assert b"xxx" == response.data308309310def test_nosubdomain(app, client):311 app.config["SERVER_NAME"] = "example.com"312313 @app.route("/<company_id>")314 def view(company_id):315 return company_id316317 with app.test_request_context():318 url = flask.url_for("view", company_id="xxx")319320 with client:321 response = client.get(url)322323 assert 200 == response.status_code324 assert b"xxx" == response.data325326327def test_cli_runner_class(app):328 runner = app.test_cli_runner()329 assert isinstance(runner, FlaskCliRunner)330331 class SubRunner(FlaskCliRunner):332 pass333334 app.test_cli_runner_class = SubRunner335 runner = app.test_cli_runner()336 assert isinstance(runner, SubRunner)337338339def test_cli_invoke(app):340 @app.cli.command("hello")341 def hello_command():342 click.echo("Hello, World!")343344 runner = app.test_cli_runner()345 # invoke with command name346 result = runner.invoke(args=["hello"])347 assert "Hello" in result.output348 # invoke with command object349 result = runner.invoke(hello_command)350 assert "Hello" in result.output351352353def test_cli_custom_obj(app):354 class NS:355 called = False356357 def create_app():358 NS.called = True359 return app360361 @app.cli.command("hello")362 def hello_command():363 click.echo("Hello, World!")364365 script_info = ScriptInfo(create_app=create_app)366 runner = app.test_cli_runner()367 runner.invoke(hello_command, obj=script_info)368 assert NS.called369370371def test_client_pop_all_preserved(app, req_ctx, client):372 @app.route("/")373 def index():374 # stream_with_context pushes a third context, preserved by response375 return flask.stream_with_context("hello")376377 # req_ctx fixture pushed an initial context378 with client:379 # request pushes a second request context, preserved by client380 rv = client.get("/")381382 # close the response, releasing the context held by stream_with_context383 rv.close()384 # only req_ctx fixture should still be pushed

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 385why, one step back
385 assert _cv_app.get(None) is req_ctx