Improve user creation logic
This commit is contained in:
parent
8a3893f33d
commit
4c3dcfe0e5
|
@ -5,6 +5,8 @@ User query interface
|
|||
import re
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select, func
|
||||
|
||||
from amanuensis.db import DbContext, User
|
||||
from amanuensis.errors import ArgumentError
|
||||
|
||||
|
@ -30,11 +32,11 @@ def create_user(
|
|||
if not password:
|
||||
raise ArgumentError('Password must be provided')
|
||||
# If display name is not provided, use the username
|
||||
if not display_name.strip():
|
||||
if not display_name or not display_name.strip():
|
||||
display_name = username
|
||||
|
||||
# Query the db to make sure the username isn't taken
|
||||
if db.session.query(User.username == username).count() > 0:
|
||||
if db.session.query(func.count(User.id)).filter(User.username == username).scalar() > 0:
|
||||
raise ArgumentError('Username is already taken')
|
||||
|
||||
new_user = User(
|
||||
|
|
|
@ -27,7 +27,7 @@ def test_create(db):
|
|||
|
||||
|
||||
def test_create_user(db):
|
||||
"""New user creation"""
|
||||
"""Test new user creation."""
|
||||
kwargs = {
|
||||
'username': 'username',
|
||||
'password': 'password',
|
||||
|
@ -36,16 +36,29 @@ def test_create_user(db):
|
|||
'is_site_admin': False
|
||||
}
|
||||
|
||||
# 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
|
||||
with pytest.raises(ArgumentError):
|
||||
userq.create_user(db, **{**kwargs, 'username': 'user name'})
|
||||
|
||||
# No password
|
||||
with pytest.raises(ArgumentError):
|
||||
userq.create_user(db, **{**kwargs, 'password': None})
|
||||
|
||||
# Valid creation works and populates fields
|
||||
new_user = userq.create_user(db, **kwargs)
|
||||
assert new_user
|
||||
assert new_user.id is not None
|
||||
assert new_user.created is not None
|
||||
|
||||
# No duplicate usernames
|
||||
with pytest.raises(ArgumentError):
|
||||
duplicate = userq.create_user(db, **kwargs)
|
||||
|
||||
# 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
|
||||
|
|
Loading…
Reference in New Issue