Spaces:
Paused

File size: 9,215 Bytes
b7980f7
aa13248
b7980f7
 
 
 
 
4405ca9
b7980f7
 
 
 
 
 
 
aa13248
1049d57
b7980f7
 
 
 
 
 
aa13248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
aa13248
b7980f7
 
aa13248
 
 
 
 
 
 
 
 
0509823
b7980f7
aa13248
 
 
 
 
0509823
b7980f7
 
 
 
aa13248
b7980f7
aa13248
 
 
b7980f7
 
 
aa13248
b7980f7
 
 
 
 
aa13248
b7980f7
 
 
 
aa13248
b7980f7
 
 
 
aa13248
b7980f7
 
 
 
aa13248
 
b7980f7
 
 
aa13248
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
aa13248
b7980f7
 
 
 
aa13248
b7980f7
aa13248
b7980f7
 
aa13248
 
 
 
 
b7980f7
aa13248
 
 
b7980f7
aa13248
b7980f7
 
aa13248
b7980f7
 
 
aa13248
b7980f7
aa13248
b7980f7
 
 
aa13248
b7980f7
 
aa13248
 
 
 
 
 
 
b7980f7
 
 
aa13248
 
 
 
 
b7980f7
 
 
aa13248
b7980f7
 
aa13248
b7980f7
aa13248
b7980f7
aa13248
b7980f7
 
 
 
aa13248
b7980f7
 
aa13248
 
 
 
 
b7980f7
 
 
aa13248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
aa13248
b7980f7
 
 
aa13248
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import asyncio
import os
import pytest
import uuid
import sys
from httpx import AsyncClient, ASGITransport
from main import app
from core.database import Base
from sqlalchemy.ext.asyncio import AsyncSession
from typing import AsyncGenerator
from unittest.mock import AsyncMock
from models.workspace import Workspace
from models.user import User, UserRole
from core.security import get_password_hash

if sys.platform == "win32":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from sqlalchemy.pool import NullPool
from core.config import get_settings

settings = get_settings()

# ---------------------------------------------------------------------------
# TEST DATABASE SAFETY
# Tests MUST NOT touch production data. This function resolves the database
# URL to use and hard-fails if there is any risk of hitting a production DB.
#
# Priority:
#   1. TEST_DATABASE_URL env var (recommended for CI and local dev)
#   2. DATABASE_URL — accepted ONLY if it clearly points to localhost / a
#      database whose name contains "test"
# ---------------------------------------------------------------------------

_SAFE_URL_SIGNALS = ["test", "localhost", "127.0.0.1", "::1", ":memory:", "mem"]


def _get_safe_test_db_url() -> str:
    explicit = os.environ.get("TEST_DATABASE_URL", "").strip()
    if explicit:
        return explicit

    fallback = settings.async_database_url
    raw = (settings.DATABASE_URL or "").lower()
    if not any(sig in raw for sig in _SAFE_URL_SIGNALS):
        raise RuntimeError(
            "\n\n"
            "  *** DESTRUCTIVE TEST BLOCKED — production database detected ***\n"
            "\n"
            "  Tests would DROP ALL TABLES in the connected database.\n"
            "\n"
            "  Fix: set TEST_DATABASE_URL to a dedicated test database URL.\n"
            "  Example:\n"
            "    TEST_DATABASE_URL=postgresql+psycopg://user:pw@localhost/nexus_test\n"
            f"\n  Detected host: {settings.database_host}\n"
        )
    return fallback


_TEST_DB_URL = _get_safe_test_db_url()

test_engine = create_async_engine(_TEST_DB_URL, poolclass=NullPool, future=True)
test_async_session_factory = async_sessionmaker(
    test_engine, class_=AsyncSession, expire_on_commit=False
)


# ---------------------------------------------------------------------------
# DATABASE SETUP FIXTURE
# Drops and recreates the entire schema once per test function that requests
# it (directly or transitively via the token fixtures below).  This guarantees
# every test starts from a clean, predictable state confined to the TEST
# database — production data is never touched.
# ---------------------------------------------------------------------------

@pytest.fixture(scope="function")
async def setup_database():
    """
    Wipes the test database, recreates the schema, and seeds baseline data.
    All test data lives in the TEST_DATABASE_URL — never in production.
    """
    from sqlalchemy import text

    async with test_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector"))
        await conn.run_sync(Base.metadata.create_all)

    async with test_async_session_factory() as db:
        from models.user_workspace import UserWorkspace

        # --- Workspace A ---
        ws_a_id = uuid.uuid4()
        ws_a = Workspace(id=ws_a_id, name="Test Workspace A")
        db.add(ws_a)

        admin_a = User(
            email="admin@a.com",
            full_name="Admin A",
            hashed_password=get_password_hash("password123"),
            global_role=UserRole.SC_ADMIN,
            is_active=True,
        )
        db.add(admin_a)
        await db.flush()
        db.add(UserWorkspace(user_id=admin_a.id, workspace_id=ws_a_id, role=UserRole.SC_ADMIN, is_primary=True))

        cust_a = User(
            email="customer@a.com",
            full_name="Customer A",
            hashed_password=get_password_hash("password123"),
            is_active=True,
        )
        db.add(cust_a)
        await db.flush()
        db.add(UserWorkspace(user_id=cust_a.id, workspace_id=ws_a_id, role=UserRole.CUSTOMER_USER, is_primary=True))

        # --- Workspace B ---
        ws_b_id = uuid.uuid4()
        ws_b = Workspace(id=ws_b_id, name="Test Workspace B")
        db.add(ws_b)

        admin_b = User(
            email="admin@b.com",
            full_name="Admin B",
            hashed_password=get_password_hash("password123"),
            global_role=UserRole.SC_ADMIN,
            is_active=True,
        )
        db.add(admin_b)
        await db.flush()
        db.add(UserWorkspace(user_id=admin_b.id, workspace_id=ws_b_id, role=UserRole.SC_ADMIN, is_primary=True))

        cust_b = User(
            email="customer@b.com",
            full_name="Customer B",
            hashed_password=get_password_hash("password123"),
            is_active=True,
        )
        db.add(cust_b)
        await db.flush()
        db.add(UserWorkspace(user_id=cust_b.id, workspace_id=ws_b_id, role=UserRole.CUSTOMER_USER, is_primary=True))

        await db.commit()

    yield


# ---------------------------------------------------------------------------
# HTTP CLIENT
# ---------------------------------------------------------------------------

@pytest.fixture
async def client(setup_database) -> AsyncGenerator[AsyncClient, None]:
    """Async HTTP client wired to the test database. Depends on setup_database
    so the schema is always seeded before any request is made."""
    from core.deps import get_arq_pool, get_db

    mock_arq = AsyncMock()
    app.dependency_overrides[get_arq_pool] = lambda: mock_arq

    async def override_get_db():
        async with test_async_session_factory() as session:
            yield session

    app.dependency_overrides[get_db] = override_get_db

    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as ac:
        yield ac

    app.dependency_overrides.clear()


# ---------------------------------------------------------------------------
# TOKEN FIXTURES
# Each fixture logs in as the corresponding seeded user.  The dependency on
# `client` (which depends on `setup_database`) ensures the test workspace is
# always ready before the login request is issued.
# ---------------------------------------------------------------------------

@pytest.fixture
async def token_a(client: AsyncClient) -> str:
    """Access token for customer@a.com (Workspace A)."""
    res = await client.post(
        "/api/v1/auth/login",
        data={"username": "customer@a.com", "password": "password123"},
    )
    assert res.status_code == 200, f"Login failed for customer@a.com: {res.text}"
    return res.json()["access_token"]


@pytest.fixture
async def admin_token_a(client: AsyncClient) -> str:
    """Access token for admin@a.com (Workspace A, SC_ADMIN)."""
    res = await client.post(
        "/api/v1/auth/login",
        data={"username": "admin@a.com", "password": "password123"},
        headers={"X-Nexus-Portal": "internal"},
    )
    assert res.status_code == 200, f"Login failed for admin@a.com: {res.text}"
    return res.json()["access_token"]


@pytest.fixture
async def token_b(client: AsyncClient) -> str:
    """Access token for customer@b.com (Workspace B)."""
    res = await client.post(
        "/api/v1/auth/login",
        data={"username": "customer@b.com", "password": "password123"},
    )
    assert res.status_code == 200, f"Login failed for customer@b.com: {res.text}"
    return res.json()["access_token"]


@pytest.fixture
async def admin_token_b(client: AsyncClient) -> str:
    """Access token for admin@b.com (Workspace B, SC_ADMIN)."""
    res = await client.post(
        "/api/v1/auth/login",
        data={"username": "admin@b.com", "password": "password123"},
        headers={"X-Nexus-Portal": "internal"},
    )
    assert res.status_code == 200, f"Login failed for admin@b.com: {res.text}"
    return res.json()["access_token"]


# ---------------------------------------------------------------------------
# DATABASE SESSION (for direct DB assertions in tests)
# ---------------------------------------------------------------------------

@pytest.fixture
async def db_session(setup_database) -> AsyncGenerator[AsyncSession, None]:
    async with test_async_session_factory() as db:
        yield db


# ---------------------------------------------------------------------------
# WORKSPACE ID HELPERS
# ---------------------------------------------------------------------------

@pytest.fixture
async def workspace_a_id(db_session: AsyncSession) -> str:
    from sqlalchemy import select
    stmt = select(Workspace).where(Workspace.name == "Test Workspace A")
    ws = (await db_session.execute(stmt)).scalar_one()
    return str(ws.id)


@pytest.fixture
async def workspace_b_id(db_session: AsyncSession) -> str:
    from sqlalchemy import select
    stmt = select(Workspace).where(Workspace.name == "Test Workspace B")
    ws = (await db_session.execute(stmt)).scalar_one()
    return str(ws.id)