Files
AIPortPilot/backend/tests/test_companies.py
T
selfrelease 8fe8047429 feat(backend): T1.2 企业档案 CRUD — 列表/详情/创建/更新/删除
- 路由:GET/POST/PUT/DELETE /api/v1/companies
- 支持分页、关键词搜索、行业/阶段筛选
- 租户隔离:只能操作本租户企业
- 测试:11 个企业 CRUD 测试,全部 passed(总计 26 tests)
2026-07-18 21:57:02 +08:00

225 lines
7.1 KiB
Python

"""企业档案 CRUD 测试。"""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from app.core.database import Base, get_db
from app.main import app
TEST_DATABASE_URL = "sqlite+aiosqlite:///file::memory:?cache=shared&uri=true"
test_engine = create_async_engine(TEST_DATABASE_URL, echo=False)
test_session_factory = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
async def override_get_db():
"""测试用数据库 session。"""
async with test_session_factory() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
app.dependency_overrides[get_db] = override_get_db
@pytest.fixture(scope="module", autouse=True)
async def setup_db():
"""创建测试数据库表。"""
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest.fixture
def client():
return TestClient(app)
@pytest.fixture
def auth_headers(client: TestClient):
"""注册并登录,返回认证头。"""
client.post(
"/api/v1/auth/register",
json={
"email": "company_test@example.com",
"password": "password123",
"name": "测试投资经理",
"tenant_name": "测试机构",
"role": "investor",
},
)
resp = client.post(
"/api/v1/auth/login",
json={"email": "company_test@example.com", "password": "password123"},
)
token = resp.json()["data"]["access_token"]
return {"Authorization": f"Bearer {token}"}
class TestCreateCompany:
"""创建企业测试。"""
def test_create_success(self, client: TestClient, auth_headers: dict):
"""正常创建企业。"""
response = client.post(
"/api/v1/companies",
json={
"name": "AI科技初创公司",
"industry": "人工智能",
"stage": "seed",
"description": "专注于AI投后管理",
"website": "https://example.com",
},
headers=auth_headers,
)
assert response.status_code == 201
data = response.json()
assert data["code"] == 0
assert data["data"]["name"] == "AI科技初创公司"
assert data["data"]["industry"] == "人工智能"
def test_create_without_auth(self, client: TestClient):
"""无认证应返回 401。"""
response = client.post(
"/api/v1/companies",
json={"name": "测试公司"},
)
assert response.status_code == 401
def test_create_empty_name(self, client: TestClient, auth_headers: dict):
"""空名称应返回 422。"""
response = client.post(
"/api/v1/companies",
json={"name": ""},
headers=auth_headers,
)
assert response.status_code == 422
class TestListCompanies:
"""企业列表测试。"""
def test_list_success(self, client: TestClient, auth_headers: dict):
"""获取企业列表。"""
response = client.get("/api/v1/companies", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["code"] == 0
assert data["data"]["total"] >= 1
assert len(data["data"]["items"]) >= 1
def test_list_with_keyword(self, client: TestClient, auth_headers: dict):
"""关键词搜索。"""
response = client.get(
"/api/v1/companies?keyword=AI科技",
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert all("AI科技" in item["name"] for item in data["data"]["items"])
def test_list_pagination(self, client: TestClient, auth_headers: dict):
"""分页参数。"""
response = client.get(
"/api/v1/companies?page=1&page_size=5",
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert data["data"]["page"] == 1
assert data["data"]["page_size"] == 5
class TestGetCompany:
"""获取企业详情测试。"""
def test_get_success(self, client: TestClient, auth_headers: dict):
"""正常获取详情。"""
# 先创建
create_resp = client.post(
"/api/v1/companies",
json={"name": "详情测试公司", "industry": "SaaS"},
headers=auth_headers,
)
company_id = create_resp.json()["data"]["id"]
response = client.get(
f"/api/v1/companies/{company_id}",
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert data["data"]["name"] == "详情测试公司"
def test_get_nonexistent(self, client: TestClient, auth_headers: dict):
"""不存在的 ID 应返回 404。"""
response = client.get(
"/api/v1/companies/nonexistent-id",
headers=auth_headers,
)
assert response.status_code == 404
class TestUpdateCompany:
"""更新企业测试。"""
def test_update_success(self, client: TestClient, auth_headers: dict):
"""正常更新。"""
create_resp = client.post(
"/api/v1/companies",
json={"name": "更新前公司", "industry": "电商"},
headers=auth_headers,
)
company_id = create_resp.json()["data"]["id"]
response = client.put(
f"/api/v1/companies/{company_id}",
json={"name": "更新后公司", "stage": "a"},
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert data["data"]["name"] == "更新后公司"
assert data["data"]["stage"] == "a"
assert data["data"]["industry"] == "电商" # 未更新的字段保持不变
class TestDeleteCompany:
"""删除企业测试。"""
def test_delete_success(self, client: TestClient, auth_headers: dict):
"""正常删除。"""
create_resp = client.post(
"/api/v1/companies",
json={"name": "待删除公司"},
headers=auth_headers,
)
company_id = create_resp.json()["data"]["id"]
response = client.delete(
f"/api/v1/companies/{company_id}",
headers=auth_headers,
)
assert response.status_code == 200
# 验证已删除
get_resp = client.get(
f"/api/v1/companies/{company_id}",
headers=auth_headers,
)
assert get_resp.status_code == 404
def test_delete_nonexistent(self, client: TestClient, auth_headers: dict):
"""删除不存在的企业应返回 404。"""
response = client.delete(
"/api/v1/companies/nonexistent-id",
headers=auth_headers,
)
assert response.status_code == 404