Spaces:
Paused

File size: 5,156 Bytes
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
import asyncio
import pytest
import uuid
import sys
from httpx import AsyncClient, ASGITransport
from main import app
from core.database import async_session_factory, Base, engine
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.WindowsProactorEventLoopPolicy())

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_engine = create_async_engine(
    settings.async_database_url,
    poolclass=NullPool,
    future=True
)
test_async_session_factory = async_sessionmaker(
    test_engine,
    class_=AsyncSession,
    expire_on_commit=False,
)

# --- DATABASE SETUP (ONCE PER TEST) ---
@pytest.fixture(scope="function", autouse=True)
async def setup_database():
    """Wipes and seeds the database for testing. BE CAREFUL with DATABASE_URL."""
    async with test_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        from sqlalchemy import text
        await conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector"))
        await conn.run_sync(Base.metadata.create_all)
    
    # Seed minimal test data
    async with test_async_session_factory() as db:
        ws_a_id = uuid.uuid4()
        ws_a = Workspace(id=ws_a_id, name="Test Workspace A")
        db.add(ws_a)
        
        from models.user_workspace import UserWorkspace
        # password is 'password123'
        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()
        
        # Link Admin A to Workspace A
        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()
        
        # Link Customer A to Workspace A
        db.add(UserWorkspace(user_id=cust_a.id, workspace_id=ws_a_id, role=UserRole.CUSTOMER_USER, is_primary=True))
        
        ws_b_id = uuid.uuid4()
        ws_b = Workspace(id=ws_b_id, name="Test Workspace B")
        db.add(ws_b)
        
        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()
        
        # Link Customer B to Workspace B
        db.add(UserWorkspace(user_id=cust_b.id, workspace_id=ws_b_id, role=UserRole.CUSTOMER_USER, is_primary=True))
        
        await db.commit()
    
    yield

# --- ASYNC CLIENT FIXTURE ---
@pytest.fixture
async def client() -> AsyncGenerator[AsyncClient, None]:
    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 ---

@pytest.fixture
async def token_a(client: AsyncClient) -> str:
    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:
    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:
    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 db_session() -> AsyncGenerator[AsyncSession, None]:
    async with test_async_session_factory() as db:
        yield db

@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)