Spaces:
Paused

File size: 5,439 Bytes
f8553c9
 
 
46efd9c
f8553c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46efd9c
 
 
 
f8553c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46efd9c
 
 
 
f8553c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import pytest
from fastapi.testclient import TestClient
from unittest.mock import patch, MagicMock
import bcrypt

from app.main import app
from app.data.initial_tools import INITIAL_TOOLS_DATA

client = TestClient(app)

# --- Fixtures for Mocking Supabase ---

@pytest.fixture
def mock_supabase():
    """Mocks the Supabase client used in the routers."""
    with patch("app.routers.auth.supabase") as mock_auth, \
         patch("app.routers.tools.supabase") as mock_tools:
        
        # We'll configure specific return values in the test functions using this mock object
        mock_client = MagicMock()
        mock_auth.table.return_value = mock_client
        mock_tools.table.return_value = mock_client
        
        # We also need to mock the initial condition where `if not supabase:` is checked
        # By patching the object itself, it evaluates to True
        
        yield mock_client

# --- Helper Classes bridging MagicMock chains ---
class MockResponse:
    def __init__(self, data):
        self.data = data

# --- Tests for Authentication ---

def test_register_success(mock_supabase):
    mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[])
    
    # Mocking insert().execute()
    mock_supabase.insert.return_value.execute.return_value = MockResponse(data=[{
        "id": "123e4567-e89b-12d3-a456-426614174000",
        "email": "test@example.com",
        "password_hash": "hashed_pw",
        "created_at": "2024-01-01T00:00:00Z"
    }])
    
    response = client.post("/api/auth/register", json={"email": "test@example.com", "password": "password123"})
    
    assert response.status_code == 200
    assert response.json()["message"] == "User registered successfully"
    assert "password_hash" not in response.json()["user"]
    assert response.json()["user"]["email"] == "test@example.com"

def test_register_existing_user(mock_supabase):
    # Mock finding an existing user
    mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{
        "id": "123", "email": "test@example.com"
    }])
    
    response = client.post("/api/auth/register", json={"email": "test@example.com", "password": "password123"})
    
    assert response.status_code == 400
    assert response.json()["detail"] == "Email already registered"

def test_login_success(mock_supabase):
    password = "password123"
    password_bytes = password.encode('utf-8')[:72]
    salt = bcrypt.gensalt()
    hashed_password = bcrypt.hashpw(password_bytes, salt).decode('utf-8')
    
    # Mock finding the user during login
    mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{
        "id": "123e4567-e89b-12d3-a456-426614174000",
        "email": "test@example.com",
        "password_hash": hashed_password
    }])
    
    response = client.post("/api/auth/login", json={"email": "test@example.com", "password": "password123"})
    
    assert response.status_code == 200
    assert response.json()["message"] == "Login successful"
    assert "password_hash" not in response.json()["user"]

def test_login_invalid_password(mock_supabase):
    password = "different_password"
    password_bytes = password.encode('utf-8')[:72]
    salt = bcrypt.gensalt()
    hashed_password = bcrypt.hashpw(password_bytes, salt).decode('utf-8')
    
    mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{
        "id": "123e4567-e89b-12d3-a456-426614174000",
        "email": "test@example.com",
        "password_hash": hashed_password
    }])
    
    response = client.post("/api/auth/login", json={"email": "test@example.com", "password": "password123"})
    
    assert response.status_code == 401
    assert response.json()["detail"] == "Invalid credentials"

def test_login_user_not_found(mock_supabase):
    mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[])
    
    response = client.post("/api/auth/login", json={"email": "notfound@example.com", "password": "password123"})
    
    assert response.status_code == 401
    assert response.json()["detail"] == "Invalid credentials"

# --- Tests for Tools ---

def test_get_tools(mock_supabase):
    mock_data = [
        {
            "id": "prompt-1", "name": "Test Tool", "description": "Desc", "url": "url",
            "category": "prompt", "tags": [], "likes": 5, "added_at": 123456, "image_url": "img",
            "i18n": {}, "user_id": "test_user_uuid"
        }
    ]
    mock_supabase.select.return_value.execute.return_value = MockResponse(data=mock_data)
    
    response = client.get("/api/tools/")
    
    assert response.status_code == 200
    assert isinstance(response.json(), list)
    assert len(response.json()) == 1
    assert response.json()[0]["name"] == "Test Tool"
    assert response.json()[0]["addedAt"] == 123456  # Testing snake_case to camelCase conversion

def test_init_tools(mock_supabase):
    admin_uuid = "123e4567-e89b-12d3-a456-426614174000"
    
    # Mocking the upsert operation length
    mock_supabase.upsert.return_value.execute.return_value = MockResponse(data=INITIAL_TOOLS_DATA)
    
    response = client.post(f"/api/tools/init?admin_user_id={admin_uuid}")
    
    assert response.status_code == 200
    assert "Successfully initialized" in response.json()["message"]
    assert response.json()["data"] == INITIAL_TOOLS_DATA