Buckets:

download
raw
10.2 kB
"""
Smart tests for api/auth.py module.
Tests cover:
1. Module importability
2. Password hashing and verification
3. JWT token creation and decoding
4. Token verification
5. Permission checking
6. API key management
"""
from datetime import datetime, timedelta, timezone
import jwt
import pytest
class TestAuthImportable:
"""Test that auth module can be imported."""
def test_module_importable(self):
"""Test that auth module can be imported."""
import api.auth as auth
assert auth is not None
def test_all_functions_available(self):
"""Test that all functions are available."""
from api.auth import (
create_access_token,
decode_token,
get_password_hash,
verify_password,
)
assert verify_password is not None
assert get_password_hash is not None
assert create_access_token is not None
assert decode_token is not None
class TestPasswordFunctions:
"""Test password hashing and verification functions."""
def test_password_hash_creation(self):
"""Test that password hash is created."""
from api.auth import get_password_hash
password = "testpassword123"
hashed = get_password_hash(password)
assert hashed is not None
assert hashed != password
assert len(hashed) > 0
def test_password_verification_success(self):
"""Test successful password verification."""
from api.auth import get_password_hash, verify_password
password = "testpassword123"
hashed = get_password_hash(password)
assert verify_password(password, hashed) is True
def test_password_verification_failure(self):
"""Test failed password verification."""
from api.auth import get_password_hash, verify_password
password = "testpassword123"
wrong_password = "wrongpassword"
hashed = get_password_hash(password)
assert verify_password(wrong_password, hashed) is False
def test_password_hash_different_each_time(self):
"""Test that password hash is different each time."""
from api.auth import get_password_hash
password = "testpassword123"
hash1 = get_password_hash(password)
hash2 = get_password_hash(password)
assert hash1 != hash2 # Different salts
class TestJWTTokenFunctions:
"""Test JWT token creation and decoding."""
def test_create_access_token(self):
"""Test JWT token creation."""
from api.auth import create_access_token
data = {"sub": "testuser", "role": "admin"}
token = create_access_token(data)
assert token is not None
assert len(token) > 0
def test_create_access_token_with_expiry(self):
"""Test JWT token creation with custom expiry."""
from api.auth import create_access_token
data = {"sub": "testuser"}
expires = timedelta(minutes=60)
token = create_access_token(data, expires)
assert token is not None
def test_decode_token_success(self):
"""Test successful token decoding."""
from api.auth import create_access_token, decode_token
data = {"sub": "testuser", "role": "admin"}
token = create_access_token(data)
decoded = decode_token(token)
assert decoded is not None
assert decoded["sub"] == "testuser"
assert decoded["role"] == "admin"
def test_decode_token_invalid(self):
"""Test decoding invalid token."""
from api.auth import decode_token
invalid_token = "invalid.token.here"
decoded = decode_token(invalid_token)
assert decoded is None
def test_decode_token_expired(self):
"""Test decoding expired token."""
from api.auth import (
ALGORITHM,
SECRET_KEY,
decode_token,
)
data = {"sub": "testuser"}
# Create token that expired 1 hour ago
expired_time = datetime.now(timezone.utc) - timedelta(hours=1)
to_encode = data.copy()
to_encode.update({"exp": expired_time})
expired_token = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
decoded = decode_token(expired_token)
assert decoded is None
class TestTokenVerification:
"""Test token verification."""
@pytest.mark.asyncio
async def test_verify_token_success(self):
"""Test successful token verification."""
from fastapi.security import HTTPAuthorizationCredentials
from api.auth import create_access_token, verify_token
data = {"sub": "testuser", "role": "admin"}
token = create_access_token(data)
credentials = HTTPAuthorizationCredentials(scheme="Bearer", credentials=token)
result = await verify_token(credentials)
assert result is not None
assert result["sub"] == "testuser"
@pytest.mark.asyncio
async def test_verify_token_invalid(self):
"""Test verification of invalid token."""
from fastapi import HTTPException
from fastapi.security import HTTPAuthorizationCredentials
from api.auth import verify_token
credentials = HTTPAuthorizationCredentials(scheme="Bearer", credentials="invalid.token")
with pytest.raises(HTTPException) as exc_info:
await verify_token(credentials)
assert exc_info.value.status_code == 401
class TestPermissionChecking:
"""Test permission checking functions."""
def test_check_permissions_admin(self):
"""Test admin permission check."""
from api.auth import check_permissions
user = {"role": "admin"}
assert check_permissions(user, "admin") is True
assert check_permissions(user, "operator") is True
assert check_permissions(user, "viewer") is True
def test_check_permissions_operator(self):
"""Test operator permission check."""
from api.auth import check_permissions
user = {"role": "operator"}
assert check_permissions(user, "admin") is False
assert check_permissions(user, "operator") is True
assert check_permissions(user, "viewer") is True
def test_check_permissions_viewer(self):
"""Test viewer permission check."""
from api.auth import check_permissions
user = {"role": "viewer"}
assert check_permissions(user, "admin") is False
assert check_permissions(user, "operator") is False
assert check_permissions(user, "viewer") is True
def test_check_permissions_unknown_role(self):
"""Test permission check with unknown role."""
from api.auth import check_permissions
user = {"role": "unknown"}
assert check_permissions(user, "admin") is False
def test_check_permissions_no_role(self):
"""Test permission check with no role."""
from api.auth import check_permissions
user = {}
# When no role is provided, default is "viewer" (level 1)
# Required level for "viewer" is 1, so 1 >= 1 is True
result = check_permissions(user, "viewer")
# The function defaults to "viewer" role which has level 1
# and requires level 1 for "viewer", so result is True
assert result is True
class TestAPIKeyManagement:
"""Test API key management functions."""
def test_create_api_key(self):
"""Test API key creation."""
from api.auth import API_KEYS, create_api_key
# Clear existing keys
API_KEYS.clear()
key = create_api_key(user_id=1, name="Test Key")
assert key is not None
assert len(key) > 0
assert key in API_KEYS
def test_verify_api_key_success(self):
"""Test successful API key verification."""
from api.auth import API_KEYS, create_api_key, verify_api_key
# Clear existing keys
API_KEYS.clear()
key = create_api_key(user_id=1, name="Test Key")
result = verify_api_key(key)
assert result is not None
assert result["user_id"] == 1
assert result["name"] == "Test Key"
def test_verify_api_key_failure(self):
"""Test failed API key verification."""
from api.auth import verify_api_key
result = verify_api_key("invalid_key")
assert result is None
def test_revoke_api_key_success(self):
"""Test successful API key revocation."""
from api.auth import (
API_KEYS,
create_api_key,
revoke_api_key,
verify_api_key,
)
# Clear existing keys
API_KEYS.clear()
key = create_api_key(user_id=1, name="Test Key")
assert verify_api_key(key) is not None
result = revoke_api_key(key)
assert result is True
assert verify_api_key(key) is None
def test_revoke_api_key_failure(self):
"""Test failed API key revocation."""
from api.auth import revoke_api_key
result = revoke_api_key("nonexistent_key")
assert result is False
class TestEmptyInput:
"""Test handling of empty input."""
def test_empty_password_hash(self):
"""Test hashing empty password."""
from api.auth import get_password_hash, verify_password
password = ""
hashed = get_password_hash(password)
assert hashed is not None
assert verify_password(password, hashed) is True
def test_empty_token_decode(self):
"""Test decoding empty token."""
from api.auth import decode_token
result = decode_token("")
assert result is None
class TestInvalidOutput:
"""Test handling of invalid output."""
def test_malformed_token(self):
"""Test decoding malformed token."""
from api.auth import decode_token
result = decode_token("not.a.valid.token")
assert result is None
def test_token_with_special_chars(self):
"""Test decoding token with special characters."""
from api.auth import decode_token
result = decode_token("token@#$%^&*")
assert result is None

Xet Storage Details

Size:
10.2 kB
·
Xet hash:
b3fafb7534a27c681dacceaa5c58a2c85d640fe2e91070cf95110131ca59d91c

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.