Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

399 lines · 10.4 KiB · Python

Last changed by

bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc

History of this file

Take it

1import importlib.metadata23import click4import pytest56import flask7from flask import appcontext_popped8from flask.cli import ScriptInfo9from flask.globals import _cv_request10from flask.json import jsonify11from 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/"404142def test_environ_base_default(app, client):43    @app.route("/")44    def index():45        flask.g.remote_addr = flask.request.remote_addr46        flask.g.user_agent = flask.request.user_agent.string47        return ""4849    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        )555657def test_environ_base_modified(app, client):58    @app.route("/")59    def index():60        flask.g.remote_addr = flask.request.remote_addr61        flask.g.user_agent = flask.request.user_agent.string62        return ""6364    client.environ_base["REMOTE_ADDR"] = "192.168.0.22"65    client.environ_base["HTTP_USER_AGENT"] = "Foo"6667    with client:68        client.get("/")69        assert flask.g.remote_addr == "192.168.0.22"70        assert flask.g.user_agent == "Foo"717273def 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/"139140141def test_redirect_keep_session(app, client, app_ctx):142    @app.route("/", methods=["GET", "POST"])143    def index():144        if flask.request.method == "POST":145            return flask.redirect("/getsession")146        flask.session["data"] = "foo"147        return "index"148149    @app.route("/getsession")150    def get_session():151        return flask.session.get("data", "<missing>")152153    with client:154        rv = client.get("/getsession")155        assert rv.data == b"<missing>"156157        rv = client.get("/")158        assert rv.data == b"index"159        assert flask.session.get("data") == "foo"160161        rv = client.post("/", data={}, follow_redirects=True)162        assert rv.data == b"foo"163        assert flask.session.get("data") == "foo"164165        rv = client.get("/getsession")166        assert rv.data == b"foo"167168169def test_session_transactions(app, client):170    @app.route("/")171    def index():172        return str(flask.session["foo"])173174    with client:175        with client.session_transaction() as sess:176            assert len(sess) == 0177            sess["foo"] = [42]178            assert len(sess) == 1179        rv = client.get("/")180        assert rv.data == b"[42]"181        with client.session_transaction() as sess:182            assert len(sess) == 1183            assert sess["foo"] == [42]184185186def test_session_transactions_no_null_sessions():187    app = flask.Flask(__name__)188189    with app.test_client() as c:190        with pytest.raises(RuntimeError) as e:191            with c.session_transaction():192                pass193        assert "Session backend did not open a session" in str(e.value)194195196def test_session_transactions_keep_context(app, client, req_ctx):197    client.get("/")198    req = flask.request._get_current_object()199    assert req is not None200    with client.session_transaction():201        assert req is flask.request._get_current_object()202203204def test_session_transaction_needs_cookies(app):205    c = app.test_client(use_cookies=False)206207    with pytest.raises(TypeError, match="Cookies are disabled."):208        with c.session_transaction():209            pass210211212def test_test_client_context_binding(app, client):213    app.testing = False214215    @app.route("/")216    def index():217        flask.g.value = 42218        return "Hello World!"219220    @app.route("/other")221    def other():222        1 // 0223224    with client:225        resp = client.get("/")226        assert flask.g.value == 42227        assert resp.data == b"Hello World!"228        assert resp.status_code == 200229230        resp = client.get("/other")231        assert not hasattr(flask.g, "value")232        assert b"Internal Server Error" in resp.data233        assert resp.status_code == 500234        flask.g.value = 23235236    try:237        flask.g.value238    except (AttributeError, RuntimeError):239        pass240    else:241        raise AssertionError("some kind of exception expected")242243244def test_reuse_client(client):245    c = client246247    with c:248        assert client.get("/").status_code == 404249250    with c:251        assert client.get("/").status_code == 404252253254def test_full_url_request(app, client):255    @app.route("/action", methods=["POST"])256    def action():257        return "x"258259    with client:260        rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})261        assert rv.status_code == 200262        assert "gin" in flask.request.form263        assert "vodka" in flask.request.args264265266def test_json_request_and_response(app, client):267    @app.route("/echo", methods=["POST"])268    def echo():269        return jsonify(flask.request.get_json())270271    with client:272        json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}273        rv = client.post("/echo", json=json_data)274275        # Request should be in JSON276        assert flask.request.is_json277        assert flask.request.get_json() == json_data278279        # Response should be in JSON280        assert rv.status_code == 200281        assert rv.is_json282        assert rv.get_json() == json_data283284285def test_client_json_no_app_context(app, client):286    @app.route("/hello", methods=["POST"])287    def hello():288        return f"Hello, {flask.request.json['name']}!"289290    class Namespace:291        count = 0292293        def add(self, app):294            self.count += 1295296    ns = Namespace()297298    with appcontext_popped.connected_to(ns.add, app):299        rv = client.post("/hello", json={"name": "Flask"})300301    assert rv.get_data(as_text=True) == "Hello, Flask!"302    assert ns.count == 1303304305def test_subdomain():306    app = flask.Flask(__name__, subdomain_matching=True)307    app.config["SERVER_NAME"] = "example.com"308    client = app.test_client()309310    @app.route("/", subdomain="<company_id>")311    def view(company_id):312        return company_id313314    with app.test_request_context():315        url = flask.url_for("view", company_id="xxx")316317    with client:318        response = client.get(url)319320    assert 200 == response.status_code321    assert b"xxx" == response.data322323324def test_nosubdomain(app, client):325    app.config["SERVER_NAME"] = "example.com"326327    @app.route("/<company_id>")328    def view(company_id):329        return company_id330331    with app.test_request_context():332        url = flask.url_for("view", company_id="xxx")333334    with client:335        response = client.get(url)336337    assert 200 == response.status_code338    assert b"xxx" == response.data339340341def test_cli_runner_class(app):342    runner = app.test_cli_runner()343    assert isinstance(runner, FlaskCliRunner)344345    class SubRunner(FlaskCliRunner):346        pass347348    app.test_cli_runner_class = SubRunner349    runner = app.test_cli_runner()350    assert isinstance(runner, SubRunner)351352353def test_cli_invoke(app):354    @app.cli.command("hello")355    def hello_command():356        click.echo("Hello, World!")357358    runner = app.test_cli_runner()359    # invoke with command name360    result = runner.invoke(args=["hello"])361    assert "Hello" in result.output362    # invoke with command object363    result = runner.invoke(hello_command)364    assert "Hello" in result.output365366367def test_cli_custom_obj(app):368    class NS:369        called = False370371    def create_app():372        NS.called = True373        return app374375    @app.cli.command("hello")376    def hello_command():377        click.echo("Hello, World!")378379    script_info = ScriptInfo(create_app=create_app)380    runner = app.test_cli_runner()381    runner.invoke(hello_command, obj=script_info)382    assert NS.called383384385def test_client_pop_all_preserved(app, req_ctx, client):386    @app.route("/")387    def index():388        # stream_with_context pushes a third context, preserved by response389        return flask.stream_with_context("hello")390391    # req_ctx fixture pushed an initial context392    with client:393        # request pushes a second request context, preserved by client394        rv = client.get("/")395396    # close the response, releasing the context held by stream_with_context397    rv.close()398    # only req_ctx fixture should still be pushed399    assert _cv_request.get(None) is req_ctx