tasklert-api / tests /unit /test_auth_service.py
hashir-qt's picture
initial deploy
507973e
Raw History Blame Contribute Delete
3.07 kB
"""Unit tests for authentication service."""
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from src.core.security import verify_password, decode_token
from src.models.user import UserRegister, UserLogin
from src.services.auth_service import register, login
@pytest.mark.asyncio
async def test_register_creates_user_and_token(test_session: AsyncSession):
"""Test that registration creates a user and returns a token."""
data = UserRegister(
email="newuser@example.com",
password="securepass123",
name="New User",
)
user, token = await register(test_session, data)
assert user.id is not None
assert user.email == data.email
assert user.name == data.name
assert user.is_active is True
assert verify_password("securepass123", user.hashed_password)
assert token is not None
# Verify token contains user_id
payload = decode_token(token)
assert int(payload["sub"]) == user.id
@pytest.mark.asyncio
async def test_register_duplicate_email_fails(test_session: AsyncSession):
"""Test that registering with duplicate email fails."""
data = UserRegister(
email="duplicate@example.com",
password="password123",
name="User One",
)
await register(test_session, data)
# Try to register again with same email
with pytest.raises(ValueError, match="Email already registered"):
await register(test_session, data)
@pytest.mark.asyncio
async def test_login_with_valid_credentials(test_session: AsyncSession):
"""Test login with correct credentials returns token."""
# Register a user first
register_data = UserRegister(
email="login@example.com",
password="mypassword",
name="Login User",
)
await register(test_session, register_data)
# Now login
login_data = UserLogin(email="login@example.com", password="mypassword")
user, token = await login(test_session, login_data)
assert user.email == "login@example.com"
assert token is not None
# Verify token
payload = decode_token(token)
assert int(payload["sub"]) == user.id
@pytest.mark.asyncio
async def test_login_with_wrong_password_fails(test_session: AsyncSession):
"""Test login with wrong password fails."""
# Register a user
register_data = UserRegister(
email="wrongpass@example.com",
password="correctpass",
name="Wrong Pass User",
)
await register(test_session, register_data)
# Try to login with wrong password
login_data = UserLogin(email="wrongpass@example.com", password="wrongpass")
with pytest.raises(ValueError, match="Invalid credentials"):
await login(test_session, login_data)
@pytest.mark.asyncio
async def test_login_with_nonexistent_email_fails(test_session: AsyncSession):
"""Test login with non-existent email fails."""
login_data = UserLogin(email="noexist@example.com", password="password")
with pytest.raises(ValueError, match="Invalid credentials"):
await login(test_session, login_data)