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

1import importlib.metadata23import click4import pytest56import flask7from flask import appcontext_popped8from flask.cli import ScriptInfo9from flask.globals import _cv_app10from 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_session(app, client, app_ctx):142    @app.route("/redirect")143    def index():144        flask.session["redirect"] = True145        return flask.redirect("/target")146147    @app.route("/target")148    def get_session():149        flask.session["target"] = True150        return ""151152    with client:153        client.get("/redirect", follow_redirects=True)154        assert flask.session["redirect"] is True155        assert flask.session["target"] is True156157158def 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)195196    with pytest.raises(TypeError, match="Cookies are disabled."):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():211        raise ZeroDivisionError212213    with client:214        resp = client.get("/")215        assert flask.g.value == 42216        assert resp.data == b"Hello World!"217        assert resp.status_code == 200218219    with client: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 = 23225226    with pytest.raises(RuntimeError):227        flask.g.value  # noqa: B018228229230def 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 pushed385    assert _cv_app.get(None) is req_ctx