# (c) cavaliba.com - test_user_last_login.py

from django.test import TestCase

import app_home.cache as cache
from app_data.models import DataRevision
from app_data.user import User
from tests import helper


class UserUpdateLastLoginTest(TestCase):
    def setUp(self):
        cache.clear()

    def test_update_last_login_persists_to_db(self):
        user = helper.add_user(login="loginuser")

        user.update_last_login()

        reloaded = User.from_keyname(keyname="loginuser", expand=True)
        self.assertNotEqual(reloaded.get_attribute_first("last_login"), "")

    def test_update_last_login_does_not_bump_last_update(self):
        user = helper.add_user(login="loginuser2")
        last_update_before = User.from_keyname(keyname="loginuser2").last_update

        user.update_last_login()

        reloaded = User.from_keyname(keyname="loginuser2")
        self.assertEqual(reloaded.last_update, last_update_before)

    def test_update_last_login_does_not_create_revision(self):
        # helper.add_user() saves with a real aaa, so self.aaa_revision carries
        # a username on the returned instance — a meaningful check that
        # skip_revision=True, not just a missing aaa, is what suppresses this
        user = helper.add_user(login="loginuser3")
        count_before = DataRevision.objects.filter(classname="user", keyname="loginuser3").count()

        user.update_last_login()

        self.assertEqual(
            DataRevision.objects.filter(classname="user", keyname="loginuser3").count(),
            count_before,
        )
