Team Ai
Apppublic

unveilAiDotOrg/audio-processor

sourceHugging Facemitupdated 1y agoView on Hugging Face
4likes
test_api_dependencies.py125 linesDownload Raw Back to root
1"""Unit tests for API dependencies."""2import pytest3import base644import json5from unittest.mock import patch6from fastapi import HTTPException7 8 9class TestValidateBearerToken:10    """Test cases for bearer token validation dependency."""11    12    def setup_method(self):13        """Set up test fixtures."""14        # Create a valid JWT token for testing15        header = {"alg": "HS256", "typ": "JWT"}16        payload = {"sub": "1234567890", "name": "John Doe", "iat": 1516239022}17        18        header_b64 = base64.urlsafe_b64encode(19            json.dumps(header).encode()20        ).decode().rstrip('=')21        payload_b64 = base64.urlsafe_b64encode(22            json.dumps(payload).encode()23        ).decode().rstrip('=')24        25        self.valid_token = f"{header_b64}.{payload_b64}.test_signature"26        self.valid_auth_header = f"Bearer {self.valid_token}"27    28    @pytest.mark.asyncio29    async def test_validate_bearer_token_success(self):30        """Test successful bearer token validation."""31        # Import here to avoid module loading issues during collection32        from interfaces.api.dependencies import validate_bearer_token33        34        result = await validate_bearer_token(self.valid_auth_header)35        assert result == self.valid_token36    37    @pytest.mark.asyncio38    async def test_validate_bearer_token_missing_header(self):39        """Test validation fails when Authorization header is missing."""40        from interfaces.api.dependencies import validate_bearer_token41        42        with pytest.raises(HTTPException) as exc_info:43            await validate_bearer_token(None)44        45        assert exc_info.value.status_code == 40146        assert "Missing Authorization header" in exc_info.value.detail47        assert exc_info.value.headers["WWW-Authenticate"] == "Bearer"48    49    @pytest.mark.asyncio50    async def test_validate_bearer_token_invalid_format(self):51        """Test validation fails for invalid Authorization header format."""52        from interfaces.api.dependencies import validate_bearer_token53        54        with pytest.raises(HTTPException) as exc_info:55            await validate_bearer_token("Basic dXNlcjpwYXNz")  # Basic auth instead of Bearer56        57        assert exc_info.value.status_code == 40158        assert "Invalid Authorization header format" in exc_info.value.detail59        assert exc_info.value.headers["WWW-Authenticate"] == "Bearer"60    61    @pytest.mark.asyncio62    async def test_validate_bearer_token_missing_bearer_prefix(self):63        """Test validation fails when Bearer prefix is missing."""64        from interfaces.api.dependencies import validate_bearer_token65        66        with pytest.raises(HTTPException) as exc_info:67            await validate_bearer_token(self.valid_token)  # Token without "Bearer " prefix68        69        assert exc_info.value.status_code == 40170        assert "Invalid Authorization header format" in exc_info.value.detail71    72    @pytest.mark.asyncio73    async def test_validate_bearer_token_empty_token(self):74        """Test validation fails for empty token after Bearer prefix."""75        from interfaces.api.dependencies import validate_bearer_token76        77        with pytest.raises(HTTPException) as exc_info:78            await validate_bearer_token("Bearer ")  # Bearer with no token79        80        assert exc_info.value.status_code == 40181        assert "Empty bearer token" in exc_info.value.detail82    83    @pytest.mark.asyncio84    async def test_validate_bearer_token_invalid_jwt_structure(self):85        """Test validation fails for invalid JWT token structure."""86        from interfaces.api.dependencies import validate_bearer_token87        88        with pytest.raises(HTTPException) as exc_info:89            await validate_bearer_token("Bearer invalid.token")  # Invalid JWT structure90        91        assert exc_info.value.status_code == 40192        assert "Invalid JWT token structure" in exc_info.value.detail93    94    @pytest.mark.asyncio95    async def test_validate_bearer_token_malformed_jwt(self):96        """Test validation fails for malformed JWT."""97        from interfaces.api.dependencies import validate_bearer_token98        99        with pytest.raises(HTTPException) as exc_info:100            await validate_bearer_token("Bearer not_a_jwt_at_all")101        102        assert exc_info.value.status_code == 401103        assert "Invalid JWT token structure" in exc_info.value.detail104    105    @pytest.mark.asyncio106    async def test_validate_bearer_token_case_sensitive(self):107        """Test that Bearer prefix is case sensitive."""108        with pytest.raises(HTTPException) as exc_info:109            await validate_bearer_token(f"bearer {self.valid_token}")  # lowercase 'bearer'110        111        assert exc_info.value.status_code == 401112        assert "Invalid Authorization header format" in exc_info.value.detail113    114    @pytest.mark.asyncio115    async def test_validate_bearer_token_extra_spaces(self):116        """Test handling of extra spaces in Authorization header."""117        # Should work with proper spacing118        result = await validate_bearer_token(f"Bearer {self.valid_token}")119        assert result == self.valid_token120        121        # Should fail with extra spaces122        with pytest.raises(HTTPException) as exc_info:123            await validate_bearer_token(f"Bearer  {self.valid_token}")  # Extra space124        125        assert exc_info.value.status_code == 401