1

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?

1 Answers1

2

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.

Detlef
  • 6,137
  • 2
  • 6
  • 24
  • From docs: `Response.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)` – Никита Шишкин Jun 15 '20 at 05:50
  • I have updated my answer. Perhaps this will bring us closer to the solution. I would also like to check whether within my token based authentication the respective tokens are present in the cookies. – Detlef Jun 15 '20 at 08:00
  • Thanks a lot! That decided my problem. So, the correct set_cookie request for me is `client.set_cookie('/', 'order', json.dumps(to_set))` – Никита Шишкин Jun 15 '20 at 10:20