user2297790
user2297790

Reputation: 95

Python Mock Testing to mock session

I am learning how to test functions in Python using Mock. I am trying to write a test for a simple function,

@social.route('/friends', methods=['GET', 'POST'])
def friends():
    test_val = session.get('uid')
    if test_val is None:
        return redirect(url_for('social.index'))
    else:
        return render_template("/home.html")

However, I am stuck at how to try and mock session.get('uid') value. So far, this has been my attempt,

@patch('session', return_value='')
@patch('flask.templating._render', return_value='')
def test_mocked_render(self, mocked, mock_session):
    print "mocked", repr(self.app.get('/social/friends').data)
    print "was _render called?", mocked.called

This attempt may be completely wrong and this is definitely the wrong way as I am still not able to mock session. However, can someone please guide me in the right way through this? Thanks.

Upvotes: 3

Views: 4749

Answers (1)

lord63. j
lord63. j

Reputation: 4670

Starting with Flask 0.8 we provide a so called “session transaction” which simulates the appropriate calls to open a session in the context of the test client and to modify it.

Let's give a simple example: app.py

from flask import Flask, session

app = Flask(__name__)
app.secret_key = 'very secret'


@app.route('/friends', methods=['GET', 'POST'])
def friends():
    test_val = session.get('uid')
    if test_val is None:
        return 'uid not in session'
    else:
        return 'uid in session'


if __name__ == '__main__':
    app.run(debug=True)

The test file: test_app.py

import unittest

from app import app 


class TestSession(unittest.TestCase):
    def test_mocked_session(self):
        with app.test_client() as c:
            with c.session_transaction() as sess:
                sess['uid'] = 'Bar'
            # once this is reached the session was stored
            rv = c.get('/friends')
            assert rv.data == 'uid in session'


if __name__ == '__main__':
    unittest.main()

run the tests via python test_app.py.

Documentation: Accessing and Modifying Sessions

Upvotes: 4

Related Questions