如何单元测试删除Flask.session属性

时间:2018-02-21 23:08:49

标签: python unit-testing session flask mocking

我正在尝试编写一个单元测试来测试会话模块中的一个方法,该方法从会话中清除一个名为first_name的属性。

def purge_first_name():
    session.pop('first_name', None)

这是我的单元测试课程。它在assertIsNone失败了。

class SessionTests(unittest.TestCase):

    def setUp(self):
        self.app = Flask(__name__)
        self.app.config['SECRET_KEY'] = 'testsecret'

    def test_purge_first_name_from_session(self):
        with self.app.test_client() as c:
                with c.session_transaction() as sess:
                    sess['first_name'] = 'Test'

                    with self.app.test_request_context():

                        self.assertEqual(sess['first_name'], 'Test')

                        purge_first_name()

                        self.assertIsNone(sess['first_name'])

1 个答案:

答案 0 :(得分:0)

修改您的flask_session.py以显示如何测试

session = {}


def set_session(sess):
    session = sess


def purge_first_name():
    session.pop('first_name', None)

test_flask_session.py

def test_purge_first_name_from_session(self):
    with self.app.test_client() as c:
            with c.session_transaction() as sess:
                sess['first_name'] = 'Test'

                with self.app.test_request_context():

                    self.assertEqual(sess['first_name'], 'Test')
                    # set the module session to be sess
                    flask_session.set_session(sess)
                    flask_session.purge_first_name()
                    self.assertIsNone(flask_session.session.get('first_name', None))