Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

424 lines · 11.0 KiB · Python

Last changed by

Not known.

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__)190    app.testing = True191192    with app.test_client() as c:193        with pytest.raises(RuntimeError) as e:194            with c.session_transaction():195                pass196        assert "Session backend did not open a session" in str(e.value)197198199def test_session_transactions_keep_context(app, client, req_ctx):200    client.get("/")201    req = flask.request._get_current_object()202    assert req is not None203    with client.session_transaction():204        assert req is flask.request._get_current_object()205206207def test_session_transaction_needs_cookies(app):208    c = app.test_client(use_cookies=False)209    with pytest.raises(RuntimeError) as e:210        with c.session_transaction():211            pass212    assert "cookies" in str(e.value)213214215def test_test_client_context_binding(app, client):216    app.testing = False217218    @app.route("/")219    def index():220        flask.g.value = 42221        return "Hello World!"222223    @app.route("/other")224    def other():225        1 // 0226227    with client:228        resp = client.get("/")229        assert flask.g.value == 42230        assert resp.data == b"Hello World!"231        assert resp.status_code == 200232233        resp = client.get("/other")234        assert not hasattr(flask.g, "value")235        assert b"Internal Server Error" in resp.data236        assert resp.status_code == 500237        flask.g.value = 23238239    try:240        flask.g.value241    except (AttributeError, RuntimeError):242        pass243    else:244        raise AssertionError("some kind of exception expected")245246247def test_reuse_client(client):248    c = client249250    with c:251        assert client.get("/").status_code == 404252253    with c:254        assert client.get("/").status_code == 404255256257def test_test_client_calls_teardown_handlers(app, client):258    called = []259260    @app.teardown_request261    def remember(error):262        called.append(error)263264    with client:265        assert called == []266        client.get("/")267        assert called == []268    assert called == [None]269270    del called[:]271    with client:272        assert called == []273        client.get("/")274        assert called == []275        client.get("/")276        assert called == [None]277    assert called == [None, None]278279280def test_full_url_request(app, client):281    @app.route("/action", methods=["POST"])282    def action():283        return "x"284285    with client:286        rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})287        assert rv.status_code == 200288        assert "gin" in flask.request.form289        assert "vodka" in flask.request.args290291292def test_json_request_and_response(app, client):293    @app.route("/echo", methods=["POST"])294    def echo():295        return jsonify(flask.request.get_json())296297    with client:298        json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}299        rv = client.post("/echo", json=json_data)300301        # Request should be in JSON302        assert flask.request.is_json303        assert flask.request.get_json() == json_data304305        # Response should be in JSON306        assert rv.status_code == 200307        assert rv.is_json308        assert rv.get_json() == json_data309310311@pytest.mark.skipif(blinker is None, reason="blinker is not installed")312def test_client_json_no_app_context(app, client):313    @app.route("/hello", methods=["POST"])314    def hello():315        return f"Hello, {flask.request.json['name']}!"316317    class Namespace:318        count = 0319320        def add(self, app):321            self.count += 1322323    ns = Namespace()324325    with appcontext_popped.connected_to(ns.add, app):326        rv = client.post("/hello", json={"name": "Flask"})327328    assert rv.get_data(as_text=True) == "Hello, Flask!"329    assert ns.count == 1330331332def test_subdomain():333    app = flask.Flask(__name__, subdomain_matching=True)334    app.config["SERVER_NAME"] = "example.com"335    client = app.test_client()336337    @app.route("/", subdomain="<company_id>")338    def view(company_id):339        return company_id340341    with app.test_request_context():342        url = flask.url_for("view", company_id="xxx")343344    with client:345        response = client.get(url)346347    assert 200 == response.status_code348    assert b"xxx" == response.data349350351def test_nosubdomain(app, client):352    app.config["SERVER_NAME"] = "example.com"353354    @app.route("/<company_id>")355    def view(company_id):356        return company_id357358    with app.test_request_context():359        url = flask.url_for("view", company_id="xxx")360361    with client:362        response = client.get(url)363364    assert 200 == response.status_code365    assert b"xxx" == response.data366367368def test_cli_runner_class(app):369    runner = app.test_cli_runner()370    assert isinstance(runner, FlaskCliRunner)371372    class SubRunner(FlaskCliRunner):373        pass374375    app.test_cli_runner_class = SubRunner376    runner = app.test_cli_runner()377    assert isinstance(runner, SubRunner)378379380def test_cli_invoke(app):381    @app.cli.command("hello")382    def hello_command():383        click.echo("Hello, World!")384385    runner = app.test_cli_runner()386    # invoke with command name387    result = runner.invoke(args=["hello"])388    assert "Hello" in result.output389    # invoke with command object390    result = runner.invoke(hello_command)391    assert "Hello" in result.output392393394def test_cli_custom_obj(app):395    class NS:396        called = False397398    def create_app():399        NS.called = True400        return app401402    @app.cli.command("hello")403    def hello_command():404        click.echo("Hello, World!")405406    script_info = ScriptInfo(create_app=create_app)407    runner = app.test_cli_runner()408    runner.invoke(hello_command, obj=script_info)409    assert NS.called410411412def test_client_pop_all_preserved(app, req_ctx, client):413    @app.route("/")414    def index():415        # stream_with_context pushes a third context, preserved by client416        return flask.Response(flask.stream_with_context("hello"))417418    # req_ctx fixture pushed an initial context, not marked preserved419    with client:420        # request pushes a second request context, preserved by client421        client.get("/")422423    # only req_ctx fixture should still be pushed424    assert flask._request_ctx_stack.top is req_ctx