Sanitize and modernize pytests

Some of these tests were written before some of our convenient
tooling existed. Additionally, some of the tests were not
cooperating with PEP-8 guidelines or isorted.

This commit does the following:
    - Replaces all calls to make_(user|session) with
      aurweb.db.create(Model, ...).
    - Replace calls to session.add(...) + session.commit() with
      aurweb.db.create.
    - Removes the majority of calls to (session|aurweb.db).delete(...).
    - Replaces session.query calls with aurweb.db.query.
    - Initializes all mutable globals in pytest fixture setup().
    - Makes mutable global declarations more concise:
      `var1, var2 = None, None` -> `var1 = var2 = None`
    - Defines a warning exclusion for test/test_ssh_pub_key.py.
    - Removes the aurweb.testing.models module.
    - Removes some useless pytest.fixture yielding.

As of this commit, developers should use the following guidelines
when writing tests:
    - Always use aurweb.db.(create|delete|query) for database
      operations, where possible.
    - Always define mutable globals in the style: `var1 = var2 = None`.
    - `yield` the most dependent model in pytest setup fixture **iff**
      you must delete records after test runs to maintain database
      integrity. Example: test/test_account_type.py.

This all makes the test code look and behave much cleaner.
Previously, aurweb.testing.setup_test_db was buggy and leaving
objects around in SQLAlchemy's IdentityMap.

Signed-off-by: Kevin Morris <kevr@0cost.org>
This commit is contained in:
Kevin Morris 2021-06-01 03:26:14 -07:00
parent f2121fb833
commit 38dc2bb99d
19 changed files with 160 additions and 239 deletions

View file

@ -1,25 +0,0 @@
import warnings
from sqlalchemy import exc
import aurweb.db
def make_user(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore", exc.SAWarning)
from aurweb.models.user import User
user = User(**kwargs)
aurweb.db.session.add(user)
aurweb.db.session.commit()
return user
def make_session(**kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore", exc.SAWarning)
from aurweb.models.session import Session
session = Session(**kwargs)
aurweb.db.session.add(session)
aurweb.db.session.commit()
return session

View file

@ -2,18 +2,26 @@
max-line-length = 127 max-line-length = 127
max-complexity = 10 max-complexity = 10
# Ignore some unavoidable flake8 warnings; we know this is against # aurweb/routers/accounts.py
# pycodestyle, but some of the existing codebase uses `I` variables, # Ignore some unavoidable flake8 warnings; we know this is against
# so specifically silence warnings about it in pre-defined files. # pycodestyle, but some of the existing codebase uses `I` variables,
# In E741, the 'I', 'O', 'l' are ambiguous variable names. # so specifically silence warnings about it in pre-defined files.
# Our current implementation uses these variables through HTTP # In E741, the 'I', 'O', 'l' are ambiguous variable names.
# and the FastAPI form specification wants them named as such. # Our current implementation uses these variables through HTTP
# In C901's case, our process_account_form function is way too # and the FastAPI form specification wants them named as such.
# complex for PEP (too many if statements). However, we need to # In C901's case, our process_account_form function is way too
# process these anyways, and making it any more complex would # complex for PEP (too many if statements). However, we need to
# just add confusion to the implementation. # process these anyways, and making it any more complex would
# just add confusion to the implementation.
#
# test/test_ssh_pub_key.py
# E501 is detected due to our >127 width test constant. Ignore it.
# Due to this, line width should _always_ be looked at in code reviews.
# Anything like this should be questioned.
#
per-file-ignores = per-file-ignores =
aurweb/routers/accounts.py:E741,C901 aurweb/routers/accounts.py:E741,C901
test/test_ssh_pub_key.py:E501
[isort] [isort]
line_length = 127 line_length = 127

View file

@ -2,14 +2,14 @@ import pytest
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
from aurweb.db import create, delete, query from aurweb.db import create, query
from aurweb.models.accepted_term import AcceptedTerm from aurweb.models.accepted_term import AcceptedTerm
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.term import Term from aurweb.models.term import Term
from aurweb.models.user import User from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
user, term, accepted_term = None, None, None user = term = accepted_term = None
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@ -26,11 +26,6 @@ def setup():
term = create(Term, Description="Test term", URL="https://test.term") term = create(Term, Description="Test term", URL="https://test.term")
yield term
delete(Term, Term.ID == term.ID)
delete(User, User.ID == user.ID)
def test_accepted_term(): def test_accepted_term():
accepted_term = create(AcceptedTerm, User=user, Term=term) accepted_term = create(AcceptedTerm, User=user, Term=term)
@ -40,8 +35,6 @@ def test_accepted_term():
assert accepted_term in user.accepted_terms assert accepted_term in user.accepted_terms
assert accepted_term in term.accepted assert accepted_term in term.accepted
delete(AcceptedTerm, AcceptedTerm.User == user, AcceptedTerm.Term == term)
def test_accepted_term_null_user_raises_exception(): def test_accepted_term_null_user_raises_exception():
from aurweb.db import session from aurweb.db import session

View file

@ -1,9 +1,9 @@
import pytest import pytest
from aurweb.db import create, delete, query
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.user import User from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.models import make_user
account_type = None account_type = None
@ -12,24 +12,17 @@ account_type = None
def setup(): def setup():
setup_test_db("Users") setup_test_db("Users")
from aurweb.db import session
global account_type global account_type
account_type = AccountType(AccountType="TestUser") account_type = create(AccountType, AccountType="TestUser")
session.add(account_type)
session.commit()
yield account_type yield account_type
session.delete(account_type) delete(AccountType, AccountType.ID == account_type.ID)
session.commit()
def test_account_type(): def test_account_type():
""" Test creating an AccountType, and reading its columns. """ """ Test creating an AccountType, and reading its columns. """
from aurweb.db import session
# Make sure it got created and was given an ID. # Make sure it got created and was given an ID.
assert bool(account_type.ID) assert bool(account_type.ID)
@ -39,20 +32,17 @@ def test_account_type():
"<AccountType(ID='%s', AccountType='TestUser')>" % ( "<AccountType(ID='%s', AccountType='TestUser')>" % (
account_type.ID) account_type.ID)
record = session.query(AccountType).filter( record = query(AccountType,
AccountType.AccountType == "TestUser").first() AccountType.AccountType == "TestUser").first()
assert account_type == record assert account_type == record
def test_user_account_type_relationship(): def test_user_account_type_relationship():
from aurweb.db import session user = create(User, Username="test", Email="test@example.org",
RealName="Test User", Passwd="testPassword",
user = make_user(Username="test", Email="test@example.org", AccountType=account_type)
RealName="Test User", Passwd="testPassword",
AccountType=account_type)
assert user.AccountType == account_type assert user.AccountType == account_type
assert account_type.users.filter(User.ID == user.ID).first() assert account_type.users.filter(User.ID == user.ID).first()
session.delete(user) delete(User, User.ID == user.ID)
session.commit()

View file

@ -12,14 +12,13 @@ from fastapi.testclient import TestClient
from aurweb import captcha from aurweb import captcha
from aurweb.asgi import app from aurweb.asgi import app
from aurweb.db import create, delete, query from aurweb.db import create, query
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.ban import Ban from aurweb.models.ban import Ban
from aurweb.models.session import Session from aurweb.models.session import Session
from aurweb.models.ssh_pub_key import SSHPubKey, get_fingerprint from aurweb.models.ssh_pub_key import SSHPubKey, get_fingerprint
from aurweb.models.user import User from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.models import make_user
from aurweb.testing.requests import Request from aurweb.testing.requests import Request
# Some test global constants. # Some test global constants.
@ -39,9 +38,9 @@ def setup():
account_type = query(AccountType, account_type = query(AccountType,
AccountType.AccountType == "User").first() AccountType.AccountType == "User").first()
user = make_user(Username=TEST_USERNAME, Email=TEST_EMAIL, user = create(User, Username=TEST_USERNAME, Email=TEST_EMAIL,
RealName="Test User", Passwd="testPassword", RealName="Test User", Passwd="testPassword",
AccountType=account_type) AccountType=account_type)
def test_get_passreset_authed_redirects(): def test_get_passreset_authed_redirects():
@ -751,8 +750,8 @@ def test_post_account_edit_error_unauthorized():
request = Request() request = Request()
sid = user.login(request, "testPassword") sid = user.login(request, "testPassword")
test2 = create(User, Username="test2", Email="test2@example.org", create(User, Username="test2",
Passwd="testPassword") Email="test2@example.org", Passwd="testPassword")
post_data = { post_data = {
"U": "test", "U": "test",

View file

@ -5,16 +5,14 @@ import pytest
from starlette.authentication import AuthenticationError from starlette.authentication import AuthenticationError
from aurweb.auth import BasicAuthBackend, has_credential from aurweb.auth import BasicAuthBackend, has_credential
from aurweb.db import query from aurweb.db import create, query
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.session import Session
from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.models import make_session, make_user
from aurweb.testing.requests import Request from aurweb.testing.requests import Request
# Persistent user object, initialized in our setup fixture. user = backend = request = None
user = None
backend = None
request = None
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@ -23,16 +21,11 @@ def setup():
setup_test_db("Users", "Sessions") setup_test_db("Users", "Sessions")
from aurweb.db import session
account_type = query(AccountType, account_type = query(AccountType,
AccountType.AccountType == "User").first() AccountType.AccountType == "User").first()
user = make_user(Username="test", Email="test@example.com", user = create(User, Username="test", Email="test@example.com",
RealName="Test User", Passwd="testPassword", RealName="Test User", Passwd="testPassword",
AccountType=account_type) AccountType=account_type)
session.add(user)
session.commit()
backend = BasicAuthBackend() backend = BasicAuthBackend()
request = Request() request = Request()
@ -60,8 +53,8 @@ async def test_auth_backend_invalid_sid():
async def test_auth_backend_invalid_user_id(): async def test_auth_backend_invalid_user_id():
# Create a new session with a fake user id. # Create a new session with a fake user id.
now_ts = datetime.utcnow().timestamp() now_ts = datetime.utcnow().timestamp()
make_session(UsersID=666, SessionID="realSession", create(Session, UsersID=666, SessionID="realSession",
LastUpdateTS=now_ts + 5) LastUpdateTS=now_ts + 5)
# Here, we specify a real SID; but it's user is not there. # Here, we specify a real SID; but it's user is not there.
request.cookies["AURSID"] = "realSession" request.cookies["AURSID"] = "realSession"
@ -74,8 +67,8 @@ async def test_basic_auth_backend():
# This time, everything matches up. We expect the user to # This time, everything matches up. We expect the user to
# equal the real_user. # equal the real_user.
now_ts = datetime.utcnow().timestamp() now_ts = datetime.utcnow().timestamp()
make_session(UsersID=user.ID, SessionID="realSession", create(Session, UsersID=user.ID, SessionID="realSession",
LastUpdateTS=now_ts + 5) LastUpdateTS=now_ts + 5)
_, result = await backend.authenticate(request) _, result = await backend.authenticate(request)
assert result == user assert result == user

View file

@ -8,33 +8,34 @@ from fastapi.testclient import TestClient
import aurweb.config import aurweb.config
from aurweb.asgi import app from aurweb.asgi import app
from aurweb.db import query from aurweb.db import create, query
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.session import Session from aurweb.models.session import Session
from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.models import make_user
# Some test global constants. # Some test global constants.
TEST_USERNAME = "test" TEST_USERNAME = "test"
TEST_EMAIL = "test@example.org" TEST_EMAIL = "test@example.org"
# Global mutables. # Global mutables.
client = TestClient(app) user = client = None
user = None
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def setup(): def setup():
global user global user, client
setup_test_db("Users", "Sessions", "Bans") setup_test_db("Users", "Sessions", "Bans")
account_type = query(AccountType, account_type = query(AccountType,
AccountType.AccountType == "User").first() AccountType.AccountType == "User").first()
user = make_user(Username=TEST_USERNAME, Email=TEST_EMAIL, user = create(User, Username=TEST_USERNAME, Email=TEST_EMAIL,
RealName="Test User", Passwd="testPassword", RealName="Test User", Passwd="testPassword",
AccountType=account_type) AccountType=account_type)
client = TestClient(app)
def test_login_logout(): def test_login_logout():

View file

@ -6,27 +6,23 @@ import pytest
from sqlalchemy import exc as sa_exc from sqlalchemy import exc as sa_exc
from aurweb.db import create
from aurweb.models.ban import Ban, is_banned from aurweb.models.ban import Ban, is_banned
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.requests import Request from aurweb.testing.requests import Request
ban = None ban = request = None
request = Request()
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def setup(): def setup():
from aurweb.db import session global ban, request
global ban
setup_test_db("Bans") setup_test_db("Bans")
ban = Ban(IPAddress="127.0.0.1", ts = datetime.utcnow() + timedelta(seconds=30)
BanTS=datetime.utcnow() + timedelta(seconds=30)) ban = create(Ban, IPAddress="127.0.0.1", BanTS=ts)
session.add(ban) request = Request()
session.commit()
def test_ban(): def test_ban():

View file

@ -1,102 +1,99 @@
from aurweb.exceptions import (AlreadyVotedException, AurwebException, BannedException, BrokenUpdateHookException, from aurweb import exceptions
InvalidArgumentsException, InvalidCommentException, InvalidPackageBaseException,
InvalidReasonException, InvalidRepositoryNameException, InvalidUserException,
MaintenanceException, NotVotedException, PackageBaseExistsException, PermissionDeniedException)
def test_aurweb_exception(): def test_aurweb_exception():
try: try:
raise AurwebException("test") raise exceptions.AurwebException("test")
except AurwebException as exc: except exceptions.AurwebException as exc:
assert str(exc) == "test" assert str(exc) == "test"
def test_maintenance_exception(): def test_maintenance_exception():
try: try:
raise MaintenanceException("test") raise exceptions.MaintenanceException("test")
except MaintenanceException as exc: except exceptions.MaintenanceException as exc:
assert str(exc) == "test" assert str(exc) == "test"
def test_banned_exception(): def test_banned_exception():
try: try:
raise BannedException("test") raise exceptions.BannedException("test")
except BannedException as exc: except exceptions.BannedException as exc:
assert str(exc) == "test" assert str(exc) == "test"
def test_already_voted_exception(): def test_already_voted_exception():
try: try:
raise AlreadyVotedException("test") raise exceptions.AlreadyVotedException("test")
except AlreadyVotedException as exc: except exceptions.AlreadyVotedException as exc:
assert str(exc) == "already voted for package base: test" assert str(exc) == "already voted for package base: test"
def test_broken_update_hook_exception(): def test_broken_update_hook_exception():
try: try:
raise BrokenUpdateHookException("test") raise exceptions.BrokenUpdateHookException("test")
except BrokenUpdateHookException as exc: except exceptions.BrokenUpdateHookException as exc:
assert str(exc) == "broken update hook: test" assert str(exc) == "broken update hook: test"
def test_invalid_arguments_exception(): def test_invalid_arguments_exception():
try: try:
raise InvalidArgumentsException("test") raise exceptions.InvalidArgumentsException("test")
except InvalidArgumentsException as exc: except exceptions.InvalidArgumentsException as exc:
assert str(exc) == "test" assert str(exc) == "test"
def test_invalid_packagebase_exception(): def test_invalid_packagebase_exception():
try: try:
raise InvalidPackageBaseException("test") raise exceptions.InvalidPackageBaseException("test")
except InvalidPackageBaseException as exc: except exceptions.InvalidPackageBaseException as exc:
assert str(exc) == "package base not found: test" assert str(exc) == "package base not found: test"
def test_invalid_comment_exception(): def test_invalid_comment_exception():
try: try:
raise InvalidCommentException("test") raise exceptions.InvalidCommentException("test")
except InvalidCommentException as exc: except exceptions.InvalidCommentException as exc:
assert str(exc) == "comment is too short: test" assert str(exc) == "comment is too short: test"
def test_invalid_reason_exception(): def test_invalid_reason_exception():
try: try:
raise InvalidReasonException("test") raise exceptions.InvalidReasonException("test")
except InvalidReasonException as exc: except exceptions.InvalidReasonException as exc:
assert str(exc) == "invalid reason: test" assert str(exc) == "invalid reason: test"
def test_invalid_user_exception(): def test_invalid_user_exception():
try: try:
raise InvalidUserException("test") raise exceptions.InvalidUserException("test")
except InvalidUserException as exc: except exceptions.InvalidUserException as exc:
assert str(exc) == "unknown user: test" assert str(exc) == "unknown user: test"
def test_not_voted_exception(): def test_not_voted_exception():
try: try:
raise NotVotedException("test") raise exceptions.NotVotedException("test")
except NotVotedException as exc: except exceptions.NotVotedException as exc:
assert str(exc) == "missing vote for package base: test" assert str(exc) == "missing vote for package base: test"
def test_packagebase_exists_exception(): def test_packagebase_exists_exception():
try: try:
raise PackageBaseExistsException("test") raise exceptions.PackageBaseExistsException("test")
except PackageBaseExistsException as exc: except exceptions.PackageBaseExistsException as exc:
assert str(exc) == "package base already exists: test" assert str(exc) == "package base already exists: test"
def test_permission_denied_exception(): def test_permission_denied_exception():
try: try:
raise PermissionDeniedException("test") raise exceptions.PermissionDeniedException("test")
except PermissionDeniedException as exc: except exceptions.PermissionDeniedException as exc:
assert str(exc) == "permission denied: test" assert str(exc) == "permission denied: test"
def test_repository_name_exception(): def test_repository_name_exception():
try: try:
raise InvalidRepositoryNameException("test") raise exceptions.InvalidRepositoryNameException("test")
except InvalidRepositoryNameException as exc: except exceptions.InvalidRepositoryNameException as exc:
assert str(exc) == "invalid repository name: test" assert str(exc) == "invalid repository name: test"

View file

@ -2,16 +2,20 @@ import pytest
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
from aurweb.db import create, delete, get_engine from aurweb.db import create
from aurweb.models.group import Group from aurweb.models.group import Group
from aurweb.testing import setup_test_db
@pytest.fixture(autouse=True)
def setup():
setup_test_db("Groups")
def test_group_creation(): def test_group_creation():
get_engine()
group = create(Group, Name="Test Group") group = create(Group, Name="Test Group")
assert bool(group.ID) assert bool(group.ID)
assert group.Name == "Test Group" assert group.Name == "Test Group"
delete(Group, Group.ID == group.ID)
def test_group_null_name_raises_exception(): def test_group_null_name_raises_exception():

View file

@ -23,5 +23,6 @@ def test_run():
use_alembic = True use_alembic = True
verbose = False verbose = False
aurweb.initdb.run(Args()) aurweb.initdb.run(Args())
assert aurweb.db.session.query(AccountType).filter( record = aurweb.db.query(AccountType,
AccountType.AccountType == "User").first() is not None AccountType.AccountType == "User").first()
assert record is not None

View file

@ -34,8 +34,6 @@ def setup():
Description="Test description.", Description="Test description.",
URL="https://test.package") URL="https://test.package")
yield package
def test_package(): def test_package():
from aurweb.db import session from aurweb.db import session

View file

@ -5,8 +5,8 @@ from sqlalchemy.exc import IntegrityError
from aurweb.db import create, query from aurweb.db import create, query
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.package_base import PackageBase from aurweb.models.package_base import PackageBase
from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.models import make_user
user = None user = None
@ -19,10 +19,9 @@ def setup():
account_type = query(AccountType, account_type = query(AccountType,
AccountType.AccountType == "User").first() AccountType.AccountType == "User").first()
user = make_user(Username="test", Email="test@example.org", user = create(User, Username="test", Email="test@example.org",
RealName="Test User", Passwd="testPassword", RealName="Test User", Passwd="testPassword",
AccountType=account_type) AccountType=account_type)
yield user
def test_package_base(): def test_package_base():

View file

@ -6,10 +6,10 @@ from aurweb.db import create, query
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.package_base import PackageBase from aurweb.models.package_base import PackageBase
from aurweb.models.package_keyword import PackageKeyword from aurweb.models.package_keyword import PackageKeyword
from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.models import make_user
user, pkgbase = None, None user = pkgbase = None
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@ -20,15 +20,13 @@ def setup():
account_type = query(AccountType, account_type = query(AccountType,
AccountType.AccountType == "User").first() AccountType.AccountType == "User").first()
user = make_user(Username="test", Email="test@example.org", user = create(User, Username="test", Email="test@example.org",
RealName="Test User", Passwd="testPassword", RealName="Test User", Passwd="testPassword",
AccountType=account_type) AccountType=account_type)
pkgbase = create(PackageBase, pkgbase = create(PackageBase,
Name="beautiful-package", Name="beautiful-package",
Maintainer=user) Maintainer=user)
yield pkgbase
def test_package_keyword(): def test_package_keyword():
pkg_keyword = create(PackageKeyword, pkg_keyword = create(PackageKeyword,

View file

@ -7,27 +7,28 @@ import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from aurweb.asgi import app from aurweb.asgi import app
from aurweb.db import query from aurweb.db import create, query
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.models import make_user
from aurweb.testing.requests import Request from aurweb.testing.requests import Request
client = TestClient(app) user = client = None
user = None
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def setup(): def setup():
global user global user, client
setup_test_db("Users", "Sessions") setup_test_db("Users", "Sessions")
account_type = query(AccountType, account_type = query(AccountType,
AccountType.AccountType == "User").first() AccountType.AccountType == "User").first()
user = make_user(Username="test", Email="test@example.org", user = create(User, Username="test", Email="test@example.org",
RealName="Test User", Passwd="testPassword", RealName="Test User", Passwd="testPassword",
AccountType=account_type) AccountType=account_type)
client = TestClient(app)
def test_index(): def test_index():

View file

@ -4,39 +4,38 @@ from unittest import mock
import pytest import pytest
from aurweb.db import create, query
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.session import generate_unique_sid from aurweb.models.session import Session, generate_unique_sid
from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.models import make_session, make_user
user, _session = None, None user = session = None
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def setup(): def setup():
from aurweb.db import session global user, session
global user, _session
setup_test_db("Users", "Sessions") setup_test_db("Users", "Sessions")
account_type = session.query(AccountType).filter( account_type = query(AccountType,
AccountType.AccountType == "User").first() AccountType.AccountType == "User").first()
user = make_user(Username="test", Email="test@example.org", user = create(User, Username="test", Email="test@example.org",
ResetKey="testReset", Passwd="testPassword", ResetKey="testReset", Passwd="testPassword",
AccountType=account_type) AccountType=account_type)
_session = make_session(UsersID=user.ID, SessionID="testSession", session = create(Session, UsersID=user.ID, SessionID="testSession",
LastUpdateTS=datetime.utcnow()) LastUpdateTS=datetime.utcnow())
def test_session(): def test_session():
assert _session.SessionID == "testSession" assert session.SessionID == "testSession"
assert _session.UsersID == user.ID assert session.UsersID == user.ID
def test_session_user_association(): def test_session_user_association():
# Make sure that the Session user attribute is correct. # Make sure that the Session user attribute is correct.
assert _session.User == user assert session.User == user
def test_generate_unique_sid(): def test_generate_unique_sid():

View file

@ -1,46 +1,37 @@
import pytest import pytest
from aurweb.db import query from aurweb.db import create, query
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.ssh_pub_key import SSHPubKey, get_fingerprint from aurweb.models.ssh_pub_key import SSHPubKey, get_fingerprint
from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.models import make_user
TEST_SSH_PUBKEY = """ TEST_SSH_PUBKEY = """
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCycoCi5yGCvSclH2wmNBUuwsYEzRZZBJaQquRc4ysl+Tg+/jiDkR3Zn9fIznC4KnFoyrIHzkKuePZ3bNDYwkZxkJKoWBCh4hXKDXSm87FMN0+VDC+1QxF/z0XaAGr/P6f4XukabyddypBdnHcZiplbw+YOSqcAE2TCqOlSXwNMOcF9U89UsR/Q9i9I52hlvU0q8+fZVGhou1KCowFSnHYtrr5KYJ04CXkJ13DkVf3+pjQWyrByvBcf1hGEaczlgfobrrv/y96jDhgfXucxliNKLdufDPPkii3LhhsNcDmmI1VZ3v0irKvd9WZuauqloobY84zEFcDTyjn0hxGjVeYFejm4fBnvjga0yZXORuWksdNfXWLDxFk6MDDd1jF0ExRbP+OxDuU4IVyIuDL7S3cnbf2YjGhkms/8voYT2OBE7FwNlfv98Kr0NUp51zpf55Arxn9j0Rz9xTA7FiODQgCn6iQ0SDtzUNL0IKTCw26xJY5gzMxbfpvzPQGeulx/ioM= kevr@volcano ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCycoCi5yGCvSclH2wmNBUuwsYEzRZZBJaQquRc4ysl+Tg+/jiDkR3Zn9fIznC4KnFoyrIHzkKuePZ3bNDYwkZxkJKoWBCh4hXKDXSm87FMN0+VDC+1QxF/z0XaAGr/P6f4XukabyddypBdnHcZiplbw+YOSqcAE2TCqOlSXwNMOcF9U89UsR/Q9i9I52hlvU0q8+fZVGhou1KCowFSnHYtrr5KYJ04CXkJ13DkVf3+pjQWyrByvBcf1hGEaczlgfobrrv/y96jDhgfXucxliNKLdufDPPkii3LhhsNcDmmI1VZ3v0irKvd9WZuauqloobY84zEFcDTyjn0hxGjVeYFejm4fBnvjga0yZXORuWksdNfXWLDxFk6MDDd1jF0ExRbP+OxDuU4IVyIuDL7S3cnbf2YjGhkms/8voYT2OBE7FwNlfv98Kr0NUp51zpf55Arxn9j0Rz9xTA7FiODQgCn6iQ0SDtzUNL0IKTCw26xJY5gzMxbfpvzPQGeulx/ioM= kevr@volcano
""" """
user, ssh_pub_key = None, None user = ssh_pub_key = None
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def setup(): def setup():
from aurweb.db import session
global user, ssh_pub_key global user, ssh_pub_key
setup_test_db("Users", "SSHPubKeys") setup_test_db("Users", "SSHPubKeys")
account_type = query(AccountType, account_type = query(AccountType,
AccountType.AccountType == "User").first() AccountType.AccountType == "User").first()
user = make_user(Username="test", Email="test@example.org", user = create(User, Username="test", Email="test@example.org",
RealName="Test User", Passwd="testPassword", RealName="Test User", Passwd="testPassword",
AccountType=account_type) AccountType=account_type)
assert account_type == user.AccountType assert account_type == user.AccountType
assert account_type.ID == user.AccountTypeID assert account_type.ID == user.AccountTypeID
ssh_pub_key = SSHPubKey(UserID=user.ID, ssh_pub_key = create(SSHPubKey,
Fingerprint="testFingerprint", UserID=user.ID,
PubKey="testPubKey") Fingerprint="testFingerprint",
PubKey="testPubKey")
session.add(ssh_pub_key)
session.commit()
yield ssh_pub_key
session.delete(ssh_pub_key)
session.commit()
def test_ssh_pub_key(): def test_ssh_pub_key():

View file

@ -2,13 +2,14 @@ import pytest
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
from aurweb.db import create, delete, get_engine from aurweb.db import create
from aurweb.models.term import Term from aurweb.models.term import Term
from aurweb.testing import setup_test_db
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def setup(): def setup():
get_engine() setup_test_db("Terms")
def test_term_creation(): def test_term_creation():
@ -18,7 +19,6 @@ def test_term_creation():
assert term.Description == "Term description" assert term.Description == "Term description"
assert term.URL == "https://fake_url.io" assert term.URL == "https://fake_url.io"
assert term.Revision == 1 assert term.Revision == 1
delete(Term, Term.ID == term.ID)
def test_term_null_description_raises_exception(): def test_term_null_description_raises_exception():

View file

@ -8,23 +8,20 @@ import pytest
import aurweb.auth import aurweb.auth
import aurweb.config import aurweb.config
from aurweb.db import query from aurweb.db import create, query
from aurweb.models.account_type import AccountType from aurweb.models.account_type import AccountType
from aurweb.models.ban import Ban from aurweb.models.ban import Ban
from aurweb.models.session import Session from aurweb.models.session import Session
from aurweb.models.ssh_pub_key import SSHPubKey from aurweb.models.ssh_pub_key import SSHPubKey
from aurweb.models.user import User from aurweb.models.user import User
from aurweb.testing import setup_test_db from aurweb.testing import setup_test_db
from aurweb.testing.models import make_session, make_user
from aurweb.testing.requests import Request from aurweb.testing.requests import Request
account_type, user = None, None account_type = user = None
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def setup(): def setup():
from aurweb.db import session
global account_type, user global account_type, user
setup_test_db("Users", "Sessions", "Bans", "SSHPubKeys") setup_test_db("Users", "Sessions", "Bans", "SSHPubKeys")
@ -32,15 +29,13 @@ def setup():
account_type = query(AccountType, account_type = query(AccountType,
AccountType.AccountType == "User").first() AccountType.AccountType == "User").first()
user = make_user(Username="test", Email="test@example.org", user = create(User, Username="test", Email="test@example.org",
RealName="Test User", Passwd="testPassword", RealName="Test User", Passwd="testPassword",
AccountType=account_type) AccountType=account_type)
def test_user_login_logout(): def test_user_login_logout():
""" Test creating a user and reading its columns. """ """ Test creating a user and reading its columns. """
from aurweb.db import session
# Assert that make_user created a valid user. # Assert that make_user created a valid user.
assert bool(user.ID) assert bool(user.ID)
@ -61,8 +56,8 @@ def test_user_login_logout():
assert "AURSID" in request.cookies assert "AURSID" in request.cookies
# Expect that User session relationships work right. # Expect that User session relationships work right.
user_session = session.query(Session).filter( user_session = query(Session,
Session.UsersID == user.ID).first() Session.UsersID == user.ID).first()
assert user_session == user.session assert user_session == user.session
assert user.session.SessionID == sid assert user.session.SessionID == sid
assert user.session.User == user assert user.session.User == user
@ -103,13 +98,9 @@ def test_user_login_twice():
def test_user_login_banned(): def test_user_login_banned():
from aurweb.db import session
# Add ban for the next 30 seconds. # Add ban for the next 30 seconds.
banned_timestamp = datetime.utcnow() + timedelta(seconds=30) banned_timestamp = datetime.utcnow() + timedelta(seconds=30)
ban = Ban(IPAddress="127.0.0.1", BanTS=banned_timestamp) create(Ban, IPAddress="127.0.0.1", BanTS=banned_timestamp)
session.add(ban)
session.commit()
request = Request() request = Request()
request.client.host = "127.0.0.1" request.client.host = "127.0.0.1"
@ -138,19 +129,14 @@ def test_legacy_user_authentication():
def test_user_login_with_outdated_sid(): def test_user_login_with_outdated_sid():
from aurweb.db import session
# Make a session with a LastUpdateTS 5 seconds ago, causing # Make a session with a LastUpdateTS 5 seconds ago, causing
# user.login to update it with a new sid. # user.login to update it with a new sid.
_session = make_session(UsersID=user.ID, SessionID="stub", create(Session, UsersID=user.ID, SessionID="stub",
LastUpdateTS=datetime.utcnow().timestamp() - 5) LastUpdateTS=datetime.utcnow().timestamp() - 5)
sid = user.login(Request(), "testPassword") sid = user.login(Request(), "testPassword")
assert sid and user.is_authenticated() assert sid and user.is_authenticated()
assert sid != "stub" assert sid != "stub"
session.delete(_session)
session.commit()
def test_user_update_password(): def test_user_update_password():
user.update_password("secondPassword") user.update_password("secondPassword")
@ -169,21 +155,14 @@ def test_user_has_credential():
def test_user_ssh_pub_key(): def test_user_ssh_pub_key():
from aurweb.db import session
assert user.ssh_pub_key is None assert user.ssh_pub_key is None
ssh_pub_key = SSHPubKey(UserID=user.ID, ssh_pub_key = create(SSHPubKey, UserID=user.ID,
Fingerprint="testFingerprint", Fingerprint="testFingerprint",
PubKey="testPubKey") PubKey="testPubKey")
session.add(ssh_pub_key)
session.commit()
assert user.ssh_pub_key == ssh_pub_key assert user.ssh_pub_key == ssh_pub_key
session.delete(ssh_pub_key)
session.commit()
def test_user_credential_types(): def test_user_credential_types():
from aurweb.db import session from aurweb.db import session
@ -203,8 +182,7 @@ def test_user_credential_types():
assert aurweb.auth.trusted_user_or_dev(user) assert aurweb.auth.trusted_user_or_dev(user)
developer_type = query(AccountType, developer_type = query(AccountType,
AccountType.AccountType == "Developer")\ AccountType.AccountType == "Developer").first()
.first()
user.AccountType = developer_type user.AccountType = developer_type
session.commit() session.commit()