Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

386 lines · 10.0 KiB · Python

Last changed by

Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.testing4    ~~~~~~~~~~~~~56    Test client and more.78    :copyright: © 2010 by the Pallets team.9    :license: BSD, see LICENSE for more details.10"""11import click12import pytest1314import flask15import werkzeug1617from flask._compat import text_type18from flask.cli import ScriptInfo19from flask.json import jsonify20from flask.testing import make_test_environ_builder, FlaskCliRunner212223def test_environ_defaults_from_config(app, client):24    app.config["SERVER_NAME"] = "example.com:1234"25    app.config["APPLICATION_ROOT"] = "/foo"2627    @app.route("/")28    def index():29        return flask.request.url3031    ctx = app.test_request_context()32    assert ctx.request.url == "http://example.com:1234/foo/"3334    rv = client.get("/")35    assert rv.data == b"http://example.com:1234/foo/"363738def test_environ_defaults(app, client, app_ctx, req_ctx):39    @app.route("/")40    def index():41        return flask.request.url4243    ctx = app.test_request_context()44    assert ctx.request.url == "http://localhost/"45    with client:46        rv = client.get("/")47        assert rv.data == b"http://localhost/"484950def test_environ_base_default(app, client, app_ctx):51    @app.route("/")52    def index():53        flask.g.user_agent = flask.request.headers["User-Agent"]54        return flask.request.remote_addr5556    rv = client.get("/")57    assert rv.data == b"127.0.0.1"58    assert flask.g.user_agent == "werkzeug/" + werkzeug.__version__596061def test_environ_base_modified(app, client, app_ctx):62    @app.route("/")63    def index():64        flask.g.user_agent = flask.request.headers["User-Agent"]65        return flask.request.remote_addr6667    client.environ_base["REMOTE_ADDR"] = "0.0.0.0"68    client.environ_base["HTTP_USER_AGENT"] = "Foo"69    rv = client.get("/")70    assert rv.data == b"0.0.0.0"71    assert flask.g.user_agent == "Foo"7273    client.environ_base["REMOTE_ADDR"] = "0.0.0.1"74    client.environ_base["HTTP_USER_AGENT"] = "Bar"75    rv = client.get("/")76    assert rv.data == b"0.0.0.1"77    assert flask.g.user_agent == "Bar"787980def test_client_open_environ(app, client, request):81    @app.route("/index")82    def index():83        return flask.request.remote_addr8485    builder = make_test_environ_builder(app, path="/index", method="GET")86    request.addfinalizer(builder.close)8788    rv = client.open(builder)89    assert rv.data == b"127.0.0.1"9091    environ = builder.get_environ()92    client.environ_base["REMOTE_ADDR"] = "127.0.0.2"93    rv = client.open(environ)94    assert rv.data == b"127.0.0.2"959697def test_specify_url_scheme(app, client):98    @app.route("/")99    def index():100        return flask.request.url101102    ctx = app.test_request_context(url_scheme="https")103    assert ctx.request.url == "https://localhost/"104105    rv = client.get("/", url_scheme="https")106    assert rv.data == b"https://localhost/"107108109def test_path_is_url(app):110    eb = make_test_environ_builder(app, "https://example.com/")111    assert eb.url_scheme == "https"112    assert eb.host == "example.com"113    assert eb.script_root == ""114    assert eb.path == "/"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/"133    assert ctx.request.blueprint == bp.name134135    rv = client.get("/", subdomain="xxx")136    assert rv.data == b"http://xxx.example.com:1234/foo/"137138139def test_redirect_keep_session(app, client, app_ctx):140    @app.route("/", methods=["GET", "POST"])141    def index():142        if flask.request.method == "POST":143            return flask.redirect("/getsession")144        flask.session["data"] = "foo"145        return "index"146147    @app.route("/getsession")148    def get_session():149        return flask.session.get("data", "<missing>")150151    with client:152        rv = client.get("/getsession")153        assert rv.data == b"<missing>"154155        rv = client.get("/")156        assert rv.data == b"index"157        assert flask.session.get("data") == "foo"158        rv = client.post("/", data={}, follow_redirects=True)159        assert rv.data == b"foo"160161        # This support requires a new Werkzeug version162        if not hasattr(client, "redirect_client"):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 text_type(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__)188    app.testing = True189190    with app.test_client() as c:191        with pytest.raises(RuntimeError) as e:192            with c.session_transaction() as sess:193                pass194        assert "Session backend did not open a session" in str(e.value)195196197def test_session_transactions_keep_context(app, client, req_ctx):198    rv = client.get("/")199    req = flask.request._get_current_object()200    assert req is not None201    with client.session_transaction():202        assert req is flask.request._get_current_object()203204205def test_session_transaction_needs_cookies(app):206    c = app.test_client(use_cookies=False)207    with pytest.raises(RuntimeError) as e:208        with c.session_transaction() as s:209            pass210    assert "cookies" in str(e.value)211212213def test_test_client_context_binding(app, client):214    app.testing = False215216    @app.route("/")217    def index():218        flask.g.value = 42219        return "Hello World!"220221    @app.route("/other")222    def other():223        1 // 0224225    with client:226        resp = client.get("/")227        assert flask.g.value == 42228        assert resp.data == b"Hello World!"229        assert resp.status_code == 200230231        resp = client.get("/other")232        assert not hasattr(flask.g, "value")233        assert b"Internal Server Error" in resp.data234        assert resp.status_code == 500235        flask.g.value = 23236237    try:238        flask.g.value239    except (AttributeError, RuntimeError):240        pass241    else:242        raise AssertionError("some kind of exception expected")243244245def test_reuse_client(client):246    c = client247248    with c:249        assert client.get("/").status_code == 404250251    with c:252        assert client.get("/").status_code == 404253254255def test_test_client_calls_teardown_handlers(app, client):256    called = []257258    @app.teardown_request259    def remember(error):260        called.append(error)261262    with client:263        assert called == []264        client.get("/")265        assert called == []266    assert called == [None]267268    del called[:]269    with client:270        assert called == []271        client.get("/")272        assert called == []273        client.get("/")274        assert called == [None]275    assert called == [None, None]276277278def test_full_url_request(app, client):279    @app.route("/action", methods=["POST"])280    def action():281        return "x"282283    with client:284        rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})285        assert rv.status_code == 200286        assert "gin" in flask.request.form287        assert "vodka" in flask.request.args288289290def test_json_request_and_response(app, client):291    @app.route("/echo", methods=["POST"])292    def echo():293        return jsonify(flask.request.get_json())294295    with client:296        json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}297        rv = client.post("/echo", json=json_data)298299        # Request should be in JSON300        assert flask.request.is_json301        assert flask.request.get_json() == json_data302303        # Response should be in JSON304        assert rv.status_code == 200305        assert rv.is_json306        assert rv.get_json() == json_data307308309def test_subdomain():310    app = flask.Flask(__name__, subdomain_matching=True)311    app.config["SERVER_NAME"] = "example.com"312    client = app.test_client()313314    @app.route("/", subdomain="<company_id>")315    def view(company_id):316        return company_id317318    with app.test_request_context():319        url = flask.url_for("view", company_id="xxx")320321    with client:322        response = client.get(url)323324    assert 200 == response.status_code325    assert b"xxx" == response.data326327328def test_nosubdomain(app, client):329    app.config["SERVER_NAME"] = "example.com"330331    @app.route("/<company_id>")332    def view(company_id):333        return company_id334335    with app.test_request_context():336        url = flask.url_for("view", company_id="xxx")337338    with client:339        response = client.get(url)340341    assert 200 == response.status_code342    assert b"xxx" == response.data343344345def test_cli_runner_class(app):346    runner = app.test_cli_runner()347    assert isinstance(runner, FlaskCliRunner)348349    class SubRunner(FlaskCliRunner):350        pass351352    app.test_cli_runner_class = SubRunner353    runner = app.test_cli_runner()354    assert isinstance(runner, SubRunner)355356357def test_cli_invoke(app):358    @app.cli.command("hello")359    def hello_command():360        click.echo("Hello, World!")361362    runner = app.test_cli_runner()363    # invoke with command name364    result = runner.invoke(args=["hello"])365    assert "Hello" in result.output366    # invoke with command object367    result = runner.invoke(hello_command)368    assert "Hello" in result.output369370371def test_cli_custom_obj(app):372    class NS(object):373        called = False374375    def create_app():376        NS.called = True377        return app378379    @app.cli.command("hello")380    def hello_command():381        click.echo("Hello, World!")382383    script_info = ScriptInfo(create_app=create_app)384    runner = app.test_cli_runner()385    runner.invoke(hello_command, obj=script_info)386    assert NS.called