Working Ninja
2021-12-31T14:10:22
Using unittest to Test Logins of a Flask App Using Flask Login

I recently wanted to test logging in different users (that didn't exist in the database) and couldn't find a clear answer for how to do so--perhaps this is a sign I am traveling where I shall not! So be it, here is my solution:

import os
import subprocess

import unittest
from unittest import mock

from app import create_app
from app.db import init_db

BASE_DIR = os.path.dirname(os.path.realpath(__file__))
DATABASE = os.path.join(BASE_DIR, 'instance', 'db-testing.sqlite3')

def client(app):
    with app.test_client() as client:
        with app.app_context():
            init_db()
        return client

class ViewsTests(unittest.TestCase):
    def setUp(self):
        app = create_app({
            'TESTING': True,
            'SECRET_KEY': '0123456789',
            'DATABASE': DATABASE
        })
        self.client = client(app)

    def tearDown(self):
        # Remove Testing Database
        subprocess.run('rm {}'.format(DATABASE))

    def test_log_in_render(self):
        rv = self.client.get('/')

        assert b'log in to continue' in rv.data

    @mock.patch('flask_login.utils._get_user')
    def test_logged_in(self, current_user):
        attrs = {
            'email': '[email protected]',
            'name': 'Foo Bar'
        }
        current_user.return_value = mock.Mock(is_authenticated=True, **attrs)

        rv = self.client.get('/')

        assert b'Logged in as Foo Bar' in rv.data

ht: https://stackoverflow.com/questions/47294304/how-to-mock-current-user-in-flask-templates/47372849#47372849