Files
PROJECT-CONTORL/backend/tests/test_custom_fields.py
beabigegg 35c90fe76b feat: implement 5 QA-driven security and quality proposals
Implemented proposals from comprehensive QA review:

1. extend-csrf-protection
   - Add POST to CSRF protected methods in frontend
   - Global CSRF middleware for all state-changing operations
   - Update tests with CSRF token fixtures

2. tighten-cors-websocket-security
   - Replace wildcard CORS with explicit method/header lists
   - Disable query parameter auth in production (code 4002)
   - Add per-user WebSocket connection limit (max 5, code 4005)

3. shorten-jwt-expiry
   - Reduce JWT expiry from 7 days to 60 minutes
   - Add refresh token support with 7-day expiry
   - Implement token rotation on refresh
   - Frontend auto-refresh when token near expiry (<5 min)

4. fix-frontend-quality
   - Add React.lazy() code splitting for all pages
   - Fix useCallback dependency arrays (Dashboard, Comments)
   - Add localStorage data validation in AuthContext
   - Complete i18n for AttachmentUpload component

5. enhance-backend-validation
   - Add SecurityAuditMiddleware for access denied logging
   - Add ErrorSanitizerMiddleware for production error messages
   - Protect /health/detailed with admin authentication
   - Add input length validation (comment 5000, desc 10000)

All 521 backend tests passing. Frontend builds successfully.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-12 23:19:05 +08:00

441 lines
15 KiB
Python

"""
Tests for Custom Fields feature.
"""
import pytest
from app.models import User, Space, Project, Task, TaskStatus, CustomField, TaskCustomValue
from app.services.formula_service import FormulaService, FormulaError, CircularReferenceError
class TestCustomFieldsCRUD:
"""Test custom fields CRUD operations."""
def setup_project(self, db, owner_id: str):
"""Create a space and project for testing."""
space = Space(
id="test-space-001",
name="Test Space",
owner_id=owner_id,
)
db.add(space)
project = Project(
id="test-project-001",
space_id=space.id,
title="Test Project",
owner_id=owner_id,
)
db.add(project)
# Add default task status
status = TaskStatus(
id="test-status-001",
project_id=project.id,
name="To Do",
color="#3B82F6",
position=0,
)
db.add(status)
db.commit()
return project
def test_create_text_field(self, client, db, auth_headers):
"""Test creating a text custom field."""
project = self.setup_project(db, "00000000-0000-0000-0000-000000000001")
response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={
"name": "Sprint Number",
"field_type": "text",
"is_required": False,
},
headers=auth_headers,
)
assert response.status_code == 201
data = response.json()
assert data["name"] == "Sprint Number"
assert data["field_type"] == "text"
assert data["is_required"] is False
def test_create_number_field(self, client, db, auth_headers):
"""Test creating a number custom field."""
project = self.setup_project(db, "00000000-0000-0000-0000-000000000001")
response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={
"name": "Story Points",
"field_type": "number",
"is_required": True,
},
headers=auth_headers,
)
assert response.status_code == 201
data = response.json()
assert data["name"] == "Story Points"
assert data["field_type"] == "number"
assert data["is_required"] is True
def test_create_dropdown_field(self, client, db, auth_headers):
"""Test creating a dropdown custom field."""
project = self.setup_project(db, "00000000-0000-0000-0000-000000000001")
response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={
"name": "Component",
"field_type": "dropdown",
"options": ["Frontend", "Backend", "Database", "API"],
"is_required": False,
},
headers=auth_headers,
)
assert response.status_code == 201
data = response.json()
assert data["name"] == "Component"
assert data["field_type"] == "dropdown"
assert data["options"] == ["Frontend", "Backend", "Database", "API"]
def test_create_dropdown_field_without_options_fails(self, client, db, auth_headers):
"""Test that creating a dropdown field without options fails."""
project = self.setup_project(db, "00000000-0000-0000-0000-000000000001")
response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={
"name": "Component",
"field_type": "dropdown",
"options": [],
},
headers=auth_headers,
)
assert response.status_code == 422 # Validation error
def test_create_formula_field(self, client, db, auth_headers):
"""Test creating a formula custom field."""
project = self.setup_project(db, "00000000-0000-0000-0000-000000000001")
# First create a number field to reference
client.post(
f"/api/projects/{project.id}/custom-fields",
json={
"name": "hours_worked",
"field_type": "number",
},
headers=auth_headers,
)
# Create formula field
response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={
"name": "Progress",
"field_type": "formula",
"formula": "{time_spent} / {original_estimate} * 100",
},
headers=auth_headers,
)
assert response.status_code == 201
data = response.json()
assert data["name"] == "Progress"
assert data["field_type"] == "formula"
assert "{time_spent}" in data["formula"]
def test_list_custom_fields(self, client, db, auth_headers):
"""Test listing custom fields for a project."""
project = self.setup_project(db, "00000000-0000-0000-0000-000000000001")
# Create some fields
client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": "Field 1", "field_type": "text"},
headers=auth_headers,
)
client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": "Field 2", "field_type": "number"},
headers=auth_headers,
)
response = client.get(
f"/api/projects/{project.id}/custom-fields",
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert data["total"] == 2
assert len(data["fields"]) == 2
def test_update_custom_field(self, client, db, auth_headers):
"""Test updating a custom field."""
project = self.setup_project(db, "00000000-0000-0000-0000-000000000001")
# Create a field
create_response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": "Original Name", "field_type": "text"},
headers=auth_headers,
)
field_id = create_response.json()["id"]
# Update it
response = client.put(
f"/api/custom-fields/{field_id}",
json={"name": "Updated Name", "is_required": True},
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert data["name"] == "Updated Name"
assert data["is_required"] is True
def test_delete_custom_field(self, client, db, auth_headers):
"""Test deleting a custom field."""
project = self.setup_project(db, "00000000-0000-0000-0000-000000000001")
# Create a field
create_response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": "To Delete", "field_type": "text"},
headers=auth_headers,
)
field_id = create_response.json()["id"]
# Delete it
response = client.delete(
f"/api/custom-fields/{field_id}",
headers=auth_headers,
)
assert response.status_code == 204
# Verify it's gone
get_response = client.get(
f"/api/custom-fields/{field_id}",
headers=auth_headers,
)
assert get_response.status_code == 404
def test_max_fields_limit(self, client, db, auth_headers):
"""Test that maximum 20 custom fields per project is enforced."""
project = self.setup_project(db, "00000000-0000-0000-0000-000000000001")
# Create 20 fields
for i in range(20):
response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": f"Field {i}", "field_type": "text"},
headers=auth_headers,
)
assert response.status_code == 201
# Try to create the 21st field
response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": "Field 21", "field_type": "text"},
headers=auth_headers,
)
assert response.status_code == 400
assert "Maximum" in response.json()["detail"]
def test_duplicate_name_rejected(self, client, db, auth_headers):
"""Test that duplicate field names are rejected."""
project = self.setup_project(db, "00000000-0000-0000-0000-000000000001")
# Create a field
client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": "Unique Name", "field_type": "text"},
headers=auth_headers,
)
# Try to create another with same name
response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": "Unique Name", "field_type": "number"},
headers=auth_headers,
)
assert response.status_code == 400
assert "already exists" in response.json()["detail"]
class TestFormulaService:
"""Test formula parsing and calculation."""
def test_extract_field_references(self):
"""Test extracting field references from formulas."""
formula = "{time_spent} / {original_estimate} * 100"
refs = FormulaService.extract_field_references(formula)
assert refs == {"time_spent", "original_estimate"}
def test_extract_multiple_references(self):
"""Test extracting multiple field references."""
formula = "{field_a} + {field_b} - {field_c}"
refs = FormulaService.extract_field_references(formula)
assert refs == {"field_a", "field_b", "field_c"}
def test_safe_eval_addition(self):
"""Test safe evaluation of addition."""
result = FormulaService._safe_eval("10 + 5")
assert float(result) == 15.0
def test_safe_eval_division(self):
"""Test safe evaluation of division."""
result = FormulaService._safe_eval("20 / 4")
assert float(result) == 5.0
def test_safe_eval_complex_expression(self):
"""Test safe evaluation of complex expression."""
result = FormulaService._safe_eval("(10 + 5) * 2 / 3")
assert float(result) == 10.0
def test_safe_eval_division_by_zero(self):
"""Test that division by zero returns 0."""
result = FormulaService._safe_eval("10 / 0")
assert float(result) == 0.0
def test_safe_eval_negative_numbers(self):
"""Test safe evaluation with negative numbers."""
result = FormulaService._safe_eval("-5 + 10")
assert float(result) == 5.0
class TestCustomValuesWithTasks:
"""Test custom values integration with tasks."""
def setup_project_with_fields(self, db, client, auth_headers, owner_id: str):
"""Create a project with custom fields for testing."""
space = Space(
id="test-space-002",
name="Test Space",
owner_id=owner_id,
)
db.add(space)
project = Project(
id="test-project-002",
space_id=space.id,
title="Test Project",
owner_id=owner_id,
)
db.add(project)
status = TaskStatus(
id="test-status-002",
project_id=project.id,
name="To Do",
color="#3B82F6",
position=0,
)
db.add(status)
db.commit()
# Create custom fields via API
text_response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": "sprint_number", "field_type": "text"},
headers=auth_headers,
)
text_field_id = text_response.json()["id"]
number_response = client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": "story_points", "field_type": "number"},
headers=auth_headers,
)
number_field_id = number_response.json()["id"]
return project, text_field_id, number_field_id
def test_create_task_with_custom_values(self, client, db, auth_headers):
"""Test creating a task with custom values."""
project, text_field_id, number_field_id = self.setup_project_with_fields(
db, client, auth_headers, "00000000-0000-0000-0000-000000000001"
)
response = client.post(
f"/api/projects/{project.id}/tasks",
json={
"title": "Test Task",
"custom_values": [
{"field_id": text_field_id, "value": "Sprint 5"},
{"field_id": number_field_id, "value": "8"},
],
},
headers=auth_headers,
)
assert response.status_code == 201
def test_get_task_includes_custom_values(self, client, db, auth_headers):
"""Test that getting a task includes custom values."""
project, text_field_id, number_field_id = self.setup_project_with_fields(
db, client, auth_headers, "00000000-0000-0000-0000-000000000001"
)
# Create task with custom values
create_response = client.post(
f"/api/projects/{project.id}/tasks",
json={
"title": "Test Task",
"custom_values": [
{"field_id": text_field_id, "value": "Sprint 5"},
{"field_id": number_field_id, "value": "8"},
],
},
headers=auth_headers,
)
task_id = create_response.json()["id"]
# Get task and check custom values
get_response = client.get(
f"/api/tasks/{task_id}",
headers=auth_headers,
)
assert get_response.status_code == 200
data = get_response.json()
assert data["custom_values"] is not None
assert len(data["custom_values"]) >= 2
def test_update_task_custom_values(self, client, db, auth_headers):
"""Test updating custom values on a task."""
project, text_field_id, number_field_id = self.setup_project_with_fields(
db, client, auth_headers, "00000000-0000-0000-0000-000000000001"
)
# Create task
create_response = client.post(
f"/api/projects/{project.id}/tasks",
json={
"title": "Test Task",
"custom_values": [
{"field_id": text_field_id, "value": "Sprint 5"},
],
},
headers=auth_headers,
)
task_id = create_response.json()["id"]
# Update custom values
update_response = client.patch(
f"/api/tasks/{task_id}",
json={
"custom_values": [
{"field_id": text_field_id, "value": "Sprint 6"},
{"field_id": number_field_id, "value": "13"},
],
},
headers=auth_headers,
)
assert update_response.status_code == 200