amanuensis/tests/test_db.py

65 lines
2.2 KiB
Python
Raw Normal View History

2021-05-05 06:05:14 +00:00
import pytest
from sqlalchemy import func
from amanuensis.db import *
2021-05-06 07:04:15 +00:00
import amanuensis.backend.user as userq
from amanuensis.errors import ArgumentError
2021-05-05 06:05:14 +00:00
@pytest.fixture
2021-05-06 07:04:15 +00:00
def db():
2021-05-05 06:05:14 +00:00
db = DbContext('sqlite:///:memory:', debug=True)
db.create_all()
2021-05-06 07:04:15 +00:00
return db
2021-05-05 06:05:14 +00:00
2021-05-06 07:04:15 +00:00
def test_create(db):
2021-05-05 06:05:14 +00:00
"""Simple test that the database creates fine from scratch."""
2021-05-06 07:04:15 +00:00
assert db.session.query(func.count(User.id)).scalar() == 0
assert db.session.query(func.count(Lexicon.id)).scalar() == 0
assert db.session.query(func.count(Membership.id)).scalar() == 0
assert db.session.query(func.count(Character.id)).scalar() == 0
assert db.session.query(func.count(Article.id)).scalar() == 0
assert db.session.query(func.count(ArticleIndex.id)).scalar() == 0
assert db.session.query(func.count(ArticleIndexRule.id)).scalar() == 0
assert db.session.query(func.count(ArticleContentRule.id)).scalar() == 0
assert db.session.query(func.count(Post.id)).scalar() == 0
def test_create_user(db):
2021-05-06 18:14:33 +00:00
"""Test new user creation."""
2021-05-06 07:04:15 +00:00
kwargs = {
'username': 'username',
'password': 'password',
'display_name': 'User Name',
'email': 'user@example.com',
'is_site_admin': False
}
2021-05-06 18:14:33 +00:00
# Test length constraints
with pytest.raises(ArgumentError):
userq.create_user(db, **{**kwargs, 'username': 'me'})
with pytest.raises(ArgumentError):
userq.create_user(db, **{**kwargs, 'username': 'the right honorable user-name, esquire'})
# Test allowed characters
2021-05-06 07:04:15 +00:00
with pytest.raises(ArgumentError):
userq.create_user(db, **{**kwargs, 'username': 'user name'})
2021-05-06 18:14:33 +00:00
# No password
2021-05-06 07:04:15 +00:00
with pytest.raises(ArgumentError):
userq.create_user(db, **{**kwargs, 'password': None})
2021-05-06 18:14:33 +00:00
# Valid creation works and populates fields
2021-05-06 07:04:15 +00:00
new_user = userq.create_user(db, **kwargs)
assert new_user
assert new_user.id is not None
assert new_user.created is not None
2021-05-06 07:09:00 +00:00
2021-05-06 18:14:33 +00:00
# No duplicate usernames
2021-05-06 07:09:00 +00:00
with pytest.raises(ArgumentError):
duplicate = userq.create_user(db, **kwargs)
2021-05-06 18:14:33 +00:00
# Missing display name populates with username
user2_kw = {**kwargs, 'username': 'user2', 'display_name': None}
user2 = userq.create_user(db, **user2_kw)
assert user2.display_name is not None