[Flask] pytest code from flask official tut "with" vs "no with" block

Hippo badrihippo at gmail.com
Mon Jun 10 08:37:47 EDT 2019


Not sure about this case, but they usually use "with" when the object needs
to be disabled or something after the block. For example, you'd use "with
open('filename.txt', 'w') as file:" so that the file automatically gets
closed after the "with" block is over.

I'm guessing "client" works in a similar fashion. (Someone else could
confirm: I'm a bit busy to investigate right now, sorry).

~Badri

On Mon, 10 Jun 2019 at 18:03, Arup Rakshit <ar at zeit.io> wrote:

> Hi,
>
> In this piece of code:
>
> def test_login(client, auth):
>     assert client.get('/auth/login').status_code == 200
>     response = auth.login()
>     assert response.headers['Location'] == 'http://localhost/'
>
>     with client:
>         client.get('/‘) # 1
>         assert session['user_id'] == 1 # 2
>         assert g.user['username'] == ‘test’ # 3
>
> Why #1, #2 and #3 is wrapped into the with block, instead of writing them
> normally like:
>
> client.get('/')
> assert session['user_id'] == 1
> assert g.user['username'] == 'test'
>
> I found the code from
> https://github.com/pallets/flask/blob/master/examples/tutorial/tests/test_auth.py#L67
>
>
> Thanks,
>
> Arup Rakshit
> ar at zeit.io
>
>
>
> _______________________________________________
> Flask mailing list
> Flask at python.org
> https://mail.python.org/mailman/listinfo/flask
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20190610/b63c7b4c/attachment.html>


More information about the Flask mailing list