Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

396 lines · 10.4 KiB · Python

Last changed by

use ruff linter and formatterDavid Lordbefore adoption54e05a2

History of this file

Take it

1import importlib.metadata23import click4import pytest56import flask7from flask import appcontext_popped8from flask.cli import ScriptInfo9from flask.globals import _cv_request10from 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_keep_session(app, client, app_ctx):142    @app.route("/", methods=["GET", "POST"])143    def index():144        if flask.request.method == "POST":145            return flask.redirect("/getsession")146        flask.session["data"] = "foo"147        return "index"148149    @app.route("/getsession")150    def get_session():151        return flask.session.get("data", "<missing>")152153    with client:154        rv = client.get("/getsession")155        assert rv.data == b"<missing>"156157        rv = client.get("/")158        assert rv.data == b"index"159        assert flask.session.get("data") == "foo"160161        rv = client.post("/", data={}, follow_redirects=True)162        assert rv.data == b"foo"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 str(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__)188189    with app.test_client() as c:190        with pytest.raises(RuntimeError) as e:191            with c.session_transaction():192                pass193        assert "Session backend did not open a session" in str(e.value)194195196def test_session_transactions_keep_context(app, client, req_ctx):197    client.get("/")198    req = flask.request._get_current_object()199    assert req is not None200    with client.session_transaction():201        assert req is flask.request._get_current_object()202203204def test_session_transaction_needs_cookies(app):205    c = app.test_client(use_cookies=False)206207    with pytest.raises(TypeError, match="Cookies are disabled."):208        with c.session_transaction():209            pass210211212def test_test_client_context_binding(app, client):213    app.testing = False214215    @app.route("/")216    def index():217        flask.g.value = 42218        return "Hello World!"219220    @app.route("/other")221    def other():222        raise ZeroDivisionError223224    with client:225        resp = client.get("/")226        assert flask.g.value == 42227        assert resp.data == b"Hello World!"228        assert resp.status_code == 200229230    with client:231        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    with pytest.raises(RuntimeError):238        flask.g.value  # noqa: B018239240241def test_reuse_client(client):242    c = client243244    with c:245        assert client.get("/").status_code == 404246247    with c:248        assert client.get("/").status_code == 404249250251def test_full_url_request(app, client):252    @app.route("/action", methods=["POST"])253    def action():254        return "x"255256    with client:257        rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})258        assert rv.status_code == 200259        assert "gin" in flask.request.form260        assert "vodka" in flask.request.args261262263def test_json_request_and_response(app, client):264    @app.route("/echo", methods=["POST"])265    def echo():266        return jsonify(flask.request.get_json())267268    with client:269        json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}270        rv = client.post("/echo", json=json_data)271272        # Request should be in JSON273        assert flask.request.is_json274        assert flask.request.get_json() == json_data275276        # Response should be in JSON277        assert rv.status_code == 200278        assert rv.is_json279        assert rv.get_json() == json_data280281282def test_client_json_no_app_context(app, client):283    @app.route("/hello", methods=["POST"])284    def hello():285        return f"Hello, {flask.request.json['name']}!"286287    class Namespace:288        count = 0289290        def add(self, app):291            self.count += 1292293    ns = Namespace()294295    with appcontext_popped.connected_to(ns.add, app):296        rv = client.post("/hello", json={"name": "Flask"})297298    assert rv.get_data(as_text=True) == "Hello, Flask!"299    assert ns.count == 1300301302def test_subdomain():303    app = flask.Flask(__name__, subdomain_matching=True)304    app.config["SERVER_NAME"] = "example.com"305    client = app.test_client()306307    @app.route("/", subdomain="<company_id>")308    def view(company_id):309        return company_id310311    with app.test_request_context():312        url = flask.url_for("view", company_id="xxx")313314    with client:315        response = client.get(url)316317    assert 200 == response.status_code318    assert b"xxx" == response.data319320321def test_nosubdomain(app, client):322    app.config["SERVER_NAME"] = "example.com"323324    @app.route("/<company_id>")325    def view(company_id):326        return company_id327328    with app.test_request_context():329        url = flask.url_for("view", company_id="xxx")330331    with client:332        response = client.get(url)333334    assert 200 == response.status_code335    assert b"xxx" == response.data336337338def test_cli_runner_class(app):339    runner = app.test_cli_runner()340    assert isinstance(runner, FlaskCliRunner)341342    class SubRunner(FlaskCliRunner):343        pass344345    app.test_cli_runner_class = SubRunner346    runner = app.test_cli_runner()347    assert isinstance(runner, SubRunner)348349350def test_cli_invoke(app):351    @app.cli.command("hello")352    def hello_command():353        click.echo("Hello, World!")354355    runner = app.test_cli_runner()356    # invoke with command name357    result = runner.invoke(args=["hello"])358    assert "Hello" in result.output359    # invoke with command object360    result = runner.invoke(hello_command)361    assert "Hello" in result.output362363364def test_cli_custom_obj(app):365    class NS:366        called = False367368    def create_app():369        NS.called = True370        return app371372    @app.cli.command("hello")373    def hello_command():374        click.echo("Hello, World!")375376    script_info = ScriptInfo(create_app=create_app)377    runner = app.test_cli_runner()378    runner.invoke(hello_command, obj=script_info)379    assert NS.called380381382def test_client_pop_all_preserved(app, req_ctx, client):383    @app.route("/")384    def index():385        # stream_with_context pushes a third context, preserved by response386        return flask.stream_with_context("hello")387388    # req_ctx fixture pushed an initial context389    with client:390        # request pushes a second request context, preserved by client391        rv = client.get("/")392393    # close the response, releasing the context held by stream_with_context394    rv.close()395    # only req_ctx fixture should still be pushed396    assert _cv_request.get(None) is req_ctx