How can I set&get cookie via testing Flask application with pytest?

I can't get cookie which I have set previously via flask.test_client. Just look

My fixture:

    @pytest.fixture(scope='module')
    def client():
        app.config['TESTING'] = True
        settings = Settings()
        ctx = app.app_context()
        ctx.push()
        with app.test_client() as client:
            yield client
        ctx.pop()
        os.system("rm -rf logs json")

And the test:

    def test_test(client):
        # order cookie is set to url_encoded '{}' by default
        to_set = {"1": 2}
        client.set_cookie('order', json.dumps(to_set))
        print(request.cookies.get('order'))  # prints url-encoded '{}'

What am I doing wrong? I need to get cookie which I had set previously for testing. How can I do that?

Upvotes: 1

Views: 2732

Answers (1)

Detlef
Detlef

Reputation: 8552

I think you forgot an argument.
Client.set_cookie(server_name, key, value)

I also know set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None) .
This refers to the Flask application object itself to set cookies in your application. It is not for testing.

I can not find the original Documentation for this but looked here.

The FlaskClient flask.testing.FlaskClient that you received from app.test_client () is derived from werkzeug.testing.Client.

The following is available in the source code of werkzeug.testing.Client.

def set_cookie (
         self,
         server_name,
         key,
         value = "",
         max_age = None,
         expires = None,
         path = "/",
         domain = None,
         secure = None,
         httponly = false,
         samesite = None,
         charset = "utf-8",
     )

(Source code files: "lib/python3.8/site-packages/werkzeug/test.py", "lib/python3.8/site-packages/flask/testing.py").

I have a similar problem in my project. There are other questions on SO on the same topic here, here and here.

Upvotes: 2

Related Questions