Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

384 lines · 10.0 KiB · Python

Last changed by

all teardown callbacks are called despite errors (#5928)David Lordbefore adoptionc34d6e8

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")7980    rv = client.open(builder)81    assert rv.data == b"127.0.0.1"8283    environ = builder.get_environ()84    client.environ_base["REMOTE_ADDR"] = "127.0.0.2"85    rv = client.open(environ)86    assert rv.data == b"127.0.0.2"878889def test_specify_url_scheme(app, client):90    @app.route("/")91    def index():92        return flask.request.url9394    ctx = app.test_request_context(url_scheme="https")95    assert ctx.request.url == "https://localhost/"9697    rv = client.get("/", url_scheme="https")98    assert rv.data == b"https://localhost/"99100101def test_path_is_url(app):102    eb = EnvironBuilder(app, "https://example.com/")103    assert eb.url_scheme == "https"104    assert eb.host == "example.com"105    assert eb.script_root == ""106    assert eb.path == "/"107108109def test_environbuilder_json_dumps(app):110    """EnvironBuilder.json_dumps() takes settings from the app."""111    app.json.ensure_ascii = False112    eb = EnvironBuilder(app, json="\u20ac")113    assert eb.input_stream.read().decode("utf8") == '"\u20ac"'114115116def test_blueprint_with_subdomain():117    app = flask.Flask(__name__, subdomain_matching=True)118    app.config["SERVER_NAME"] = "example.com:1234"119    app.config["APPLICATION_ROOT"] = "/foo"120    client = app.test_client()121122    bp = flask.Blueprint("company", __name__, subdomain="xxx")123124    @bp.route("/")125    def index():126        return flask.request.url127128    app.register_blueprint(bp)129130    ctx = app.test_request_context("/", subdomain="xxx")131    assert ctx.request.url == "http://xxx.example.com:1234/foo/"132133    with ctx:134        assert ctx.request.blueprint == bp.name135136    rv = client.get("/", subdomain="xxx")137    assert rv.data == b"http://xxx.example.com:1234/foo/"138139140def test_redirect_session(app, client, app_ctx):141    @app.route("/redirect")142    def index():143        flask.session["redirect"] = True144        return flask.redirect("/target")145146    @app.route("/target")147    def get_session():148        flask.session["target"] = True149        return ""150151    with client:152        client.get("/redirect", follow_redirects=True)153        assert flask.session["redirect"] is True154        assert flask.session["target"] is True155156157def test_session_transactions(app, client):158    @app.route("/")159    def index():160        return str(flask.session["foo"])161162    with client:163        with client.session_transaction() as sess:164            assert len(sess) == 0165            sess["foo"] = [42]166            assert len(sess) == 1167        rv = client.get("/")168        assert rv.data == b"[42]"169        with client.session_transaction() as sess:170            assert len(sess) == 1171            assert sess["foo"] == [42]172173174def test_session_transactions_no_null_sessions():175    app = flask.Flask(__name__)176177    with app.test_client() as c:178        with pytest.raises(RuntimeError) as e:179            with c.session_transaction():180                pass181        assert "Session backend did not open a session" in str(e.value)182183184def test_session_transactions_keep_context(app, client, req_ctx):185    client.get("/")186    req = flask.request._get_current_object()187    assert req is not None188    with client.session_transaction():189        assert req is flask.request._get_current_object()190191192def test_session_transaction_needs_cookies(app):193    c = app.test_client(use_cookies=False)194195    with pytest.raises(TypeError, match="Cookies are disabled."):196        with c.session_transaction():197            pass198199200def test_test_client_context_binding(app, client):201    app.testing = False202203    @app.route("/")204    def index():205        flask.g.value = 42206        return "Hello World!"207208    @app.route("/other")209    def other():210        raise ZeroDivisionError211212    with client:213        resp = client.get("/")214        assert flask.g.value == 42215        assert resp.data == b"Hello World!"216        assert resp.status_code == 200217218    with client:219        resp = client.get("/other")220        assert not hasattr(flask.g, "value")221        assert b"Internal Server Error" in resp.data222        assert resp.status_code == 500223        flask.g.value = 23224225    with pytest.raises(RuntimeError):226        flask.g.value  # noqa: B018227228229def test_reuse_client(client):230    c = client231232    with c:233        assert client.get("/").status_code == 404234235    with c:236        assert client.get("/").status_code == 404237238239def test_full_url_request(app, client):240    @app.route("/action", methods=["POST"])241    def action():242        return "x"243244    with client:245        rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})246        assert rv.status_code == 200247        assert "gin" in flask.request.form248        assert "vodka" in flask.request.args249250251def test_json_request_and_response(app, client):252    @app.route("/echo", methods=["POST"])253    def echo():254        return jsonify(flask.request.get_json())255256    with client:257        json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}258        rv = client.post("/echo", json=json_data)259260        # Request should be in JSON261        assert flask.request.is_json262        assert flask.request.get_json() == json_data263264        # Response should be in JSON265        assert rv.status_code == 200266        assert rv.is_json267        assert rv.get_json() == json_data268269270def test_client_json_no_app_context(app, client):271    @app.route("/hello", methods=["POST"])272    def hello():273        return f"Hello, {flask.request.json['name']}!"274275    class Namespace:276        count = 0277278        def add(self, app):279            self.count += 1280281    ns = Namespace()282283    with appcontext_popped.connected_to(ns.add, app):284        rv = client.post("/hello", json={"name": "Flask"})285286    assert rv.get_data(as_text=True) == "Hello, Flask!"287    assert ns.count == 1288289290def test_subdomain():291    app = flask.Flask(__name__, subdomain_matching=True)292    app.config["SERVER_NAME"] = "example.com"293    client = app.test_client()294295    @app.route("/", subdomain="<company_id>")296    def view(company_id):297        return company_id298299    with app.test_request_context():300        url = flask.url_for("view", company_id="xxx")301302    with client:303        response = client.get(url)304305    assert 200 == response.status_code306    assert b"xxx" == response.data307308309def test_nosubdomain(app, client):310    app.config["SERVER_NAME"] = "example.com"311312    @app.route("/<company_id>")313    def view(company_id):314        return company_id315316    with app.test_request_context():317        url = flask.url_for("view", company_id="xxx")318319    with client:320        response = client.get(url)321322    assert 200 == response.status_code323    assert b"xxx" == response.data324325326def test_cli_runner_class(app):327    runner = app.test_cli_runner()328    assert isinstance(runner, FlaskCliRunner)329330    class SubRunner(FlaskCliRunner):331        pass332333    app.test_cli_runner_class = SubRunner334    runner = app.test_cli_runner()335    assert isinstance(runner, SubRunner)336337338def test_cli_invoke(app):339    @app.cli.command("hello")340    def hello_command():341        click.echo("Hello, World!")342343    runner = app.test_cli_runner()344    # invoke with command name345    result = runner.invoke(args=["hello"])346    assert "Hello" in result.output347    # invoke with command object348    result = runner.invoke(hello_command)349    assert "Hello" in result.output350351352def test_cli_custom_obj(app):353    class NS:354        called = False355356    def create_app():357        NS.called = True358        return app359360    @app.cli.command("hello")361    def hello_command():362        click.echo("Hello, World!")363364    script_info = ScriptInfo(create_app=create_app)365    runner = app.test_cli_runner()366    runner.invoke(hello_command, obj=script_info)367    assert NS.called368369370def test_client_pop_all_preserved(app, req_ctx, client):371    @app.route("/")372    def index():373        # stream_with_context pushes a third context, preserved by response374        return flask.stream_with_context("hello")375376    # req_ctx fixture pushed an initial context377    with client:378        # request pushes a second request context, preserved by client379        rv = client.get("/")380381    # close the response, releasing the context held by stream_with_context382    rv.close()383    # only req_ctx fixture should still be pushed384    assert _cv_app.get(None) is req_ctx