Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

402 lines · 10.6 KiB · Python

Last changed by

Merge pull request #4666 from pallets/debug-contextDavid Lordbefore adoption6916697

History of this file

Take it

1import click2import pytest3import werkzeug45import flask6from flask import appcontext_popped7from flask.cli import ScriptInfo8from flask.json import jsonify9from flask.testing import EnvironBuilder10from flask.testing import FlaskCliRunner1112try:13    import blinker14except ImportError:15    blinker = None161718def test_environ_defaults_from_config(app, client):19    app.config["SERVER_NAME"] = "example.com:1234"20    app.config["APPLICATION_ROOT"] = "/foo"2122    @app.route("/")23    def index():24        return flask.request.url2526    ctx = app.test_request_context()27    assert ctx.request.url == "http://example.com:1234/foo/"2829    rv = client.get("/")30    assert rv.data == b"http://example.com:1234/foo/"313233def test_environ_defaults(app, client, app_ctx, req_ctx):34    @app.route("/")35    def index():36        return flask.request.url3738    ctx = app.test_request_context()39    assert ctx.request.url == "http://localhost/"40    with client:41        rv = client.get("/")42        assert rv.data == b"http://localhost/"434445def test_environ_base_default(app, client, app_ctx):46    @app.route("/")47    def index():48        flask.g.user_agent = flask.request.headers["User-Agent"]49        return flask.request.remote_addr5051    rv = client.get("/")52    assert rv.data == b"127.0.0.1"53    assert flask.g.user_agent == f"werkzeug/{werkzeug.__version__}"545556def test_environ_base_modified(app, client, app_ctx):57    @app.route("/")58    def index():59        flask.g.user_agent = flask.request.headers["User-Agent"]60        return flask.request.remote_addr6162    client.environ_base["REMOTE_ADDR"] = "0.0.0.0"63    client.environ_base["HTTP_USER_AGENT"] = "Foo"64    rv = client.get("/")65    assert rv.data == b"0.0.0.0"66    assert flask.g.user_agent == "Foo"6768    client.environ_base["REMOTE_ADDR"] = "0.0.0.1"69    client.environ_base["HTTP_USER_AGENT"] = "Bar"70    rv = client.get("/")71    assert rv.data == b"0.0.0.1"72    assert flask.g.user_agent == "Bar"737475def test_client_open_environ(app, client, request):76    @app.route("/index")77    def index():78        return flask.request.remote_addr7980    builder = EnvironBuilder(app, path="/index", method="GET")81    request.addfinalizer(builder.close)8283    rv = client.open(builder)84    assert rv.data == b"127.0.0.1"8586    environ = builder.get_environ()87    client.environ_base["REMOTE_ADDR"] = "127.0.0.2"88    rv = client.open(environ)89    assert rv.data == b"127.0.0.2"909192def test_specify_url_scheme(app, client):93    @app.route("/")94    def index():95        return flask.request.url9697    ctx = app.test_request_context(url_scheme="https")98    assert ctx.request.url == "https://localhost/"99100    rv = client.get("/", url_scheme="https")101    assert rv.data == b"https://localhost/"102103104def test_path_is_url(app):105    eb = EnvironBuilder(app, "https://example.com/")106    assert eb.url_scheme == "https"107    assert eb.host == "example.com"108    assert eb.script_root == ""109    assert eb.path == "/"110111112def test_environbuilder_json_dumps(app):113    """EnvironBuilder.json_dumps() takes settings from the app."""114    app.config["JSON_AS_ASCII"] = False115    eb = EnvironBuilder(app, json="\u20ac")116    assert eb.input_stream.read().decode("utf8") == '"\u20ac"'117118119def test_blueprint_with_subdomain():120    app = flask.Flask(__name__, subdomain_matching=True)121    app.config["SERVER_NAME"] = "example.com:1234"122    app.config["APPLICATION_ROOT"] = "/foo"123    client = app.test_client()124125    bp = flask.Blueprint("company", __name__, subdomain="xxx")126127    @bp.route("/")128    def index():129        return flask.request.url130131    app.register_blueprint(bp)132133    ctx = app.test_request_context("/", subdomain="xxx")134    assert ctx.request.url == "http://xxx.example.com:1234/foo/"135136    with ctx:137        assert ctx.request.blueprint == bp.name138139    rv = client.get("/", subdomain="xxx")140    assert rv.data == b"http://xxx.example.com:1234/foo/"141142143def test_redirect_keep_session(app, client, app_ctx):144    @app.route("/", methods=["GET", "POST"])145    def index():146        if flask.request.method == "POST":147            return flask.redirect("/getsession")148        flask.session["data"] = "foo"149        return "index"150151    @app.route("/getsession")152    def get_session():153        return flask.session.get("data", "<missing>")154155    with client:156        rv = client.get("/getsession")157        assert rv.data == b"<missing>"158159        rv = client.get("/")160        assert rv.data == b"index"161        assert flask.session.get("data") == "foo"162163        rv = client.post("/", data={}, follow_redirects=True)164        assert rv.data == b"foo"165        assert flask.session.get("data") == "foo"166167        rv = client.get("/getsession")168        assert rv.data == b"foo"169170171def test_session_transactions(app, client):172    @app.route("/")173    def index():174        return str(flask.session["foo"])175176    with client:177        with client.session_transaction() as sess:178            assert len(sess) == 0179            sess["foo"] = [42]180            assert len(sess) == 1181        rv = client.get("/")182        assert rv.data == b"[42]"183        with client.session_transaction() as sess:184            assert len(sess) == 1185            assert sess["foo"] == [42]186187188def test_session_transactions_no_null_sessions():189    app = flask.Flask(__name__)190191    with app.test_client() as c:192        with pytest.raises(RuntimeError) as e:193            with c.session_transaction():194                pass195        assert "Session backend did not open a session" in str(e.value)196197198def test_session_transactions_keep_context(app, client, req_ctx):199    client.get("/")200    req = flask.request._get_current_object()201    assert req is not None202    with client.session_transaction():203        assert req is flask.request._get_current_object()204205206def test_session_transaction_needs_cookies(app):207    c = app.test_client(use_cookies=False)208    with pytest.raises(RuntimeError) as e:209        with c.session_transaction():210            pass211    assert "cookies" in str(e.value)212213214def test_test_client_context_binding(app, client):215    app.testing = False216217    @app.route("/")218    def index():219        flask.g.value = 42220        return "Hello World!"221222    @app.route("/other")223    def other():224        1 // 0225226    with client:227        resp = client.get("/")228        assert flask.g.value == 42229        assert resp.data == b"Hello World!"230        assert resp.status_code == 200231232        resp = client.get("/other")233        assert not hasattr(flask.g, "value")234        assert b"Internal Server Error" in resp.data235        assert resp.status_code == 500236        flask.g.value = 23237238    try:239        flask.g.value240    except (AttributeError, RuntimeError):241        pass242    else:243        raise AssertionError("some kind of exception expected")244245246def test_reuse_client(client):247    c = client248249    with c:250        assert client.get("/").status_code == 404251252    with c:253        assert client.get("/").status_code == 404254255256def test_full_url_request(app, client):257    @app.route("/action", methods=["POST"])258    def action():259        return "x"260261    with client:262        rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})263        assert rv.status_code == 200264        assert "gin" in flask.request.form265        assert "vodka" in flask.request.args266267268def test_json_request_and_response(app, client):269    @app.route("/echo", methods=["POST"])270    def echo():271        return jsonify(flask.request.get_json())272273    with client:274        json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}275        rv = client.post("/echo", json=json_data)276277        # Request should be in JSON278        assert flask.request.is_json279        assert flask.request.get_json() == json_data280281        # Response should be in JSON282        assert rv.status_code == 200283        assert rv.is_json284        assert rv.get_json() == json_data285286287@pytest.mark.skipif(blinker is None, reason="blinker is not installed")288def test_client_json_no_app_context(app, client):289    @app.route("/hello", methods=["POST"])290    def hello():291        return f"Hello, {flask.request.json['name']}!"292293    class Namespace:294        count = 0295296        def add(self, app):297            self.count += 1298299    ns = Namespace()300301    with appcontext_popped.connected_to(ns.add, app):302        rv = client.post("/hello", json={"name": "Flask"})303304    assert rv.get_data(as_text=True) == "Hello, Flask!"305    assert ns.count == 1306307308def test_subdomain():309    app = flask.Flask(__name__, subdomain_matching=True)310    app.config["SERVER_NAME"] = "example.com"311    client = app.test_client()312313    @app.route("/", subdomain="<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_nosubdomain(app, client):328    app.config["SERVER_NAME"] = "example.com"329330    @app.route("/<company_id>")331    def view(company_id):332        return company_id333334    with app.test_request_context():335        url = flask.url_for("view", company_id="xxx")336337    with client:338        response = client.get(url)339340    assert 200 == response.status_code341    assert b"xxx" == response.data342343344def test_cli_runner_class(app):345    runner = app.test_cli_runner()346    assert isinstance(runner, FlaskCliRunner)347348    class SubRunner(FlaskCliRunner):349        pass350351    app.test_cli_runner_class = SubRunner352    runner = app.test_cli_runner()353    assert isinstance(runner, SubRunner)354355356def test_cli_invoke(app):357    @app.cli.command("hello")358    def hello_command():359        click.echo("Hello, World!")360361    runner = app.test_cli_runner()362    # invoke with command name363    result = runner.invoke(args=["hello"])364    assert "Hello" in result.output365    # invoke with command object366    result = runner.invoke(hello_command)367    assert "Hello" in result.output368369370def test_cli_custom_obj(app):371    class NS:372        called = False373374    def create_app():375        NS.called = True376        return app377378    @app.cli.command("hello")379    def hello_command():380        click.echo("Hello, World!")381382    script_info = ScriptInfo(create_app=create_app)383    runner = app.test_cli_runner()384    runner.invoke(hello_command, obj=script_info)385    assert NS.called386387388def test_client_pop_all_preserved(app, req_ctx, client):389    @app.route("/")390    def index():391        # stream_with_context pushes a third context, preserved by response392        return flask.stream_with_context("hello")393394    # req_ctx fixture pushed an initial context395    with client:396        # request pushes a second request context, preserved by client397        rv = client.get("/")398399    # close the response, releasing the context held by stream_with_context400    rv.close()401    # only req_ctx fixture should still be pushed402    assert flask._request_ctx_stack.top is req_ctx