How to pass a modified or custom session while making request in testing flask applications?

656 views Asked by At

I have adopted the code from manual

http://flask.pocoo.org/docs/0.10/testing/#accessing-and-modifying-sessions

with app.test_client() as c:
with c.session_transaction() as sess:
    sess['a_key'] = 'a value'

# once this is reached the session was stored

The core of my project that uses this approach is presented below.

Structure

  • /testing_with_flask
    • /test_project
      • /templates
        • index.html
      • __init__.py
    • /requirements.py
    • /run.py
    • /test.py

Content of every file

requirements.txt

Flask

run.py

from test_project import create_app

app = create_app()
app.run(host='0.0.0.0', port=8080, debug=True)

test.py

from test_project import create_app
from unittest import TestCase as Base


class TestCase(Base):
    @classmethod
    def setUpClass(cls):
        cls.app = create_app()
        cls.app.config['TESTING'] = True
        cls.client = cls.app.test_client()
        cls._ctx = cls.app.test_request_context()
        cls._ctx.push()


class TestModel(TestCase):

    def test_adding_comments_logged_user(self):
        with self.app.test_client() as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1
            self.app.preprocess_request()
            response = self.client.get('/')

        assert 'Yahooo!!!' in response.data


if __name__ == "__main__":
    import unittest    
    unittest.main()

__init__.py

# Main init file.
from flask import Flask, render_template, g, session


DEBUG = False
TESTING = False

SECRET_KEY = "jd&%G#43WG~dn6"
SITE_TITLE = "TEST"


def index():
    return render_template('index.html', user=g.user)


def load_user():
    if 'user_id' not in session.keys():
        g.user = 'None'
    else:
        g.user = 'Yahooo!!!'


def create_app():
    app = Flask(__name__)
    app.config.from_object(__name__)
    app.before_request(load_user)
    app.add_url_rule('/', 'index', index)

    return app

index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>I Need Help</title>
</head>
<body>
{{ user }}
</body>
</html>

Unfortunately, I can't get the value 'Yahooo!!!' of the variable g.user. I can not get 'else' branch of 'if' statement of the function load_user running test.py.

1

There are 1 answers

0
Andriy On BEST ANSWER

The solution is based on the code presented in similar question:

How to test session in flask resource

Instead of line

with self.app.test_client() as c:

in 'test.py' I should write

with self.client as c:

However, I still don't understand these lines difference.