test_session.py 1.55 KB
Newer Older
1
2
3
4
5
6
""" Test our Session model. """
from datetime import datetime
from unittest import mock

import pytest

Kevin Morris's avatar
Kevin Morris committed
7
from aurweb.db import create, query
8
from aurweb.models.account_type import AccountType
Kevin Morris's avatar
Kevin Morris committed
9
10
from aurweb.models.session import Session, generate_unique_sid
from aurweb.models.user import User
11
12
from aurweb.testing import setup_test_db

Kevin Morris's avatar
Kevin Morris committed
13
user = session = None
14
15
16
17


@pytest.fixture(autouse=True)
def setup():
Kevin Morris's avatar
Kevin Morris committed
18
    global user, session
19
20
21

    setup_test_db("Users", "Sessions")

Kevin Morris's avatar
Kevin Morris committed
22
23
24
25
26
27
28
    account_type = query(AccountType,
                         AccountType.AccountType == "User").first()
    user = create(User, Username="test", Email="test@example.org",
                  ResetKey="testReset", Passwd="testPassword",
                  AccountType=account_type)
    session = create(Session, UsersID=user.ID, SessionID="testSession",
                     LastUpdateTS=datetime.utcnow())
29
30
31


def test_session():
Kevin Morris's avatar
Kevin Morris committed
32
33
    assert session.SessionID == "testSession"
    assert session.UsersID == user.ID
34
35
36
37


def test_session_user_association():
    # Make sure that the Session user attribute is correct.
Kevin Morris's avatar
Kevin Morris committed
38
    assert session.User == user
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55


def test_generate_unique_sid():
    # Mock up aurweb.models.session.generate_sid by returning
    # sids[i % 2] from 0 .. n. This will swap between each sid
    # between each call.
    sids = ["testSession", "realSession"]
    i = 0

    def mock_generate_sid(length):
        nonlocal i
        sid = sids[i % 2]
        i += 1
        return sid

    with mock.patch("aurweb.util.make_random_string", mock_generate_sid):
        assert generate_unique_sid() == "realSession"