feat: implement custom fields, gantt view, calendar view, and file encryption

- Custom Fields (FEAT-001):
  - CustomField and TaskCustomValue models with formula support
  - CRUD API for custom field management
  - Formula engine for calculated fields
  - Frontend: CustomFieldEditor, CustomFieldInput, ProjectSettings page
  - Task list API now includes custom_values
  - KanbanBoard displays custom field values

- Gantt View (FEAT-003):
  - TaskDependency model with FS/SS/FF/SF dependency types
  - Dependency CRUD API with cycle detection
  - start_date field added to tasks
  - GanttChart component with Frappe Gantt integration
  - Dependency type selector in UI

- Calendar View (FEAT-004):
  - CalendarView component with FullCalendar integration
  - Date range filtering API for tasks
  - Drag-and-drop date updates
  - View mode switching in Tasks page

- File Encryption (FEAT-010):
  - AES-256-GCM encryption service
  - EncryptionKey model with key rotation support
  - Admin API for key management
  - Encrypted upload/download for confidential projects

- Migrations: 011 (custom fields), 012 (encryption keys), 013 (task dependencies)
- Updated issues.md with completion status

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
beabigegg
2026-01-05 23:39:12 +08:00
parent 69b81d9241
commit 2d80a8384e
65 changed files with 11045 additions and 82 deletions

View File

@@ -0,0 +1,440 @@
"""
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, admin_token):
"""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={"Authorization": f"Bearer {admin_token}"},
)
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, admin_token):
"""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={"Authorization": f"Bearer {admin_token}"},
)
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, admin_token):
"""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={"Authorization": f"Bearer {admin_token}"},
)
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, admin_token):
"""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={"Authorization": f"Bearer {admin_token}"},
)
assert response.status_code == 422 # Validation error
def test_create_formula_field(self, client, db, admin_token):
"""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={"Authorization": f"Bearer {admin_token}"},
)
# 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={"Authorization": f"Bearer {admin_token}"},
)
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, admin_token):
"""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={"Authorization": f"Bearer {admin_token}"},
)
client.post(
f"/api/projects/{project.id}/custom-fields",
json={"name": "Field 2", "field_type": "number"},
headers={"Authorization": f"Bearer {admin_token}"},
)
response = client.get(
f"/api/projects/{project.id}/custom-fields",
headers={"Authorization": f"Bearer {admin_token}"},
)
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, admin_token):
"""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={"Authorization": f"Bearer {admin_token}"},
)
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={"Authorization": f"Bearer {admin_token}"},
)
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, admin_token):
"""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={"Authorization": f"Bearer {admin_token}"},
)
field_id = create_response.json()["id"]
# Delete it
response = client.delete(
f"/api/custom-fields/{field_id}",
headers={"Authorization": f"Bearer {admin_token}"},
)
assert response.status_code == 204
# Verify it's gone
get_response = client.get(
f"/api/custom-fields/{field_id}",
headers={"Authorization": f"Bearer {admin_token}"},
)
assert get_response.status_code == 404
def test_max_fields_limit(self, client, db, admin_token):
"""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={"Authorization": f"Bearer {admin_token}"},
)
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={"Authorization": f"Bearer {admin_token}"},
)
assert response.status_code == 400
assert "Maximum" in response.json()["detail"]
def test_duplicate_name_rejected(self, client, db, admin_token):
"""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={"Authorization": f"Bearer {admin_token}"},
)
# 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={"Authorization": f"Bearer {admin_token}"},
)
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, admin_token, 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={"Authorization": f"Bearer {admin_token}"},
)
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={"Authorization": f"Bearer {admin_token}"},
)
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, admin_token):
"""Test creating a task with custom values."""
project, text_field_id, number_field_id = self.setup_project_with_fields(
db, client, admin_token, "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={"Authorization": f"Bearer {admin_token}"},
)
assert response.status_code == 201
def test_get_task_includes_custom_values(self, client, db, admin_token):
"""Test that getting a task includes custom values."""
project, text_field_id, number_field_id = self.setup_project_with_fields(
db, client, admin_token, "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={"Authorization": f"Bearer {admin_token}"},
)
task_id = create_response.json()["id"]
# Get task and check custom values
get_response = client.get(
f"/api/tasks/{task_id}",
headers={"Authorization": f"Bearer {admin_token}"},
)
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, admin_token):
"""Test updating custom values on a task."""
project, text_field_id, number_field_id = self.setup_project_with_fields(
db, client, admin_token, "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={"Authorization": f"Bearer {admin_token}"},
)
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={"Authorization": f"Bearer {admin_token}"},
)
assert update_response.status_code == 200

View File

@@ -0,0 +1,275 @@
"""
Tests for the file encryption functionality.
Tests cover:
- Encryption service (key generation, encrypt/decrypt)
- Encryption key management API
- Attachment upload with encryption
- Attachment download with decryption
"""
import pytest
import base64
import secrets
from io import BytesIO
from unittest.mock import patch, MagicMock
from app.services.encryption_service import (
EncryptionService,
encryption_service,
MasterKeyNotConfiguredError,
DecryptionError,
KEY_SIZE,
NONCE_SIZE,
)
class TestEncryptionService:
"""Tests for the encryption service."""
@pytest.fixture
def mock_master_key(self):
"""Generate a valid test master key."""
return base64.urlsafe_b64encode(secrets.token_bytes(32)).decode()
@pytest.fixture
def service_with_key(self, mock_master_key):
"""Create an encryption service with a mock master key."""
with patch('app.services.encryption_service.settings') as mock_settings:
mock_settings.ENCRYPTION_MASTER_KEY = mock_master_key
service = EncryptionService()
yield service
def test_generate_key(self, service_with_key):
"""Test that generate_key produces a 32-byte key."""
key = service_with_key.generate_key()
assert len(key) == KEY_SIZE
assert isinstance(key, bytes)
def test_generate_key_uniqueness(self, service_with_key):
"""Test that each generated key is unique."""
keys = [service_with_key.generate_key() for _ in range(10)]
unique_keys = set(keys)
assert len(unique_keys) == 10
def test_encrypt_decrypt_key(self, service_with_key):
"""Test encryption and decryption of a file encryption key."""
# Generate a key to encrypt
original_key = service_with_key.generate_key()
# Encrypt the key
encrypted_key = service_with_key.encrypt_key(original_key)
assert isinstance(encrypted_key, str)
assert encrypted_key != base64.urlsafe_b64encode(original_key).decode()
# Decrypt the key
decrypted_key = service_with_key.decrypt_key(encrypted_key)
assert decrypted_key == original_key
def test_encrypt_decrypt_file(self, service_with_key):
"""Test file encryption and decryption."""
# Create test file content
original_content = b"This is a test file content for encryption."
file_obj = BytesIO(original_content)
# Generate encryption key
key = service_with_key.generate_key()
# Encrypt
encrypted_content = service_with_key.encrypt_file(file_obj, key)
assert encrypted_content != original_content
assert len(encrypted_content) > len(original_content) # Due to nonce and tag
# Decrypt
encrypted_file = BytesIO(encrypted_content)
decrypted_content = service_with_key.decrypt_file(encrypted_file, key)
assert decrypted_content == original_content
def test_encrypt_decrypt_bytes(self, service_with_key):
"""Test bytes encryption and decryption convenience methods."""
original_data = b"Test data for encryption"
key = service_with_key.generate_key()
# Encrypt
encrypted_data = service_with_key.encrypt_bytes(original_data, key)
assert encrypted_data != original_data
# Decrypt
decrypted_data = service_with_key.decrypt_bytes(encrypted_data, key)
assert decrypted_data == original_data
def test_encrypt_large_file(self, service_with_key):
"""Test encryption of a larger file (1MB)."""
# Create 1MB of random data
original_content = secrets.token_bytes(1024 * 1024)
file_obj = BytesIO(original_content)
key = service_with_key.generate_key()
# Encrypt
encrypted_content = service_with_key.encrypt_file(file_obj, key)
# Decrypt
encrypted_file = BytesIO(encrypted_content)
decrypted_content = service_with_key.decrypt_file(encrypted_file, key)
assert decrypted_content == original_content
def test_decrypt_with_wrong_key(self, service_with_key):
"""Test that decryption fails with wrong key."""
original_content = b"Secret content"
file_obj = BytesIO(original_content)
key1 = service_with_key.generate_key()
key2 = service_with_key.generate_key()
# Encrypt with key1
encrypted_content = service_with_key.encrypt_file(file_obj, key1)
# Try to decrypt with key2
encrypted_file = BytesIO(encrypted_content)
with pytest.raises(DecryptionError):
service_with_key.decrypt_file(encrypted_file, key2)
def test_decrypt_corrupted_data(self, service_with_key):
"""Test that decryption fails with corrupted data."""
original_content = b"Secret content"
file_obj = BytesIO(original_content)
key = service_with_key.generate_key()
# Encrypt
encrypted_content = service_with_key.encrypt_file(file_obj, key)
# Corrupt the encrypted data
corrupted = bytearray(encrypted_content)
corrupted[20] ^= 0xFF # Flip some bits
corrupted_content = bytes(corrupted)
# Try to decrypt
encrypted_file = BytesIO(corrupted_content)
with pytest.raises(DecryptionError):
service_with_key.decrypt_file(encrypted_file, key)
def test_is_encryption_available_with_key(self, mock_master_key):
"""Test is_encryption_available returns True when key is configured."""
with patch('app.services.encryption_service.settings') as mock_settings:
mock_settings.ENCRYPTION_MASTER_KEY = mock_master_key
service = EncryptionService()
assert service.is_encryption_available() is True
def test_is_encryption_available_without_key(self):
"""Test is_encryption_available returns False when key is not configured."""
with patch('app.services.encryption_service.settings') as mock_settings:
mock_settings.ENCRYPTION_MASTER_KEY = None
service = EncryptionService()
assert service.is_encryption_available() is False
def test_master_key_not_configured_error(self):
"""Test that operations fail when master key is not configured."""
with patch('app.services.encryption_service.settings') as mock_settings:
mock_settings.ENCRYPTION_MASTER_KEY = None
service = EncryptionService()
key = secrets.token_bytes(32)
with pytest.raises(MasterKeyNotConfiguredError):
service.encrypt_key(key)
def test_encrypted_key_format(self, service_with_key):
"""Test that encrypted key is valid base64."""
key = service_with_key.generate_key()
encrypted_key = service_with_key.encrypt_key(key)
# Should be valid base64
decoded = base64.urlsafe_b64decode(encrypted_key)
# Should contain nonce + ciphertext + tag
assert len(decoded) >= NONCE_SIZE + KEY_SIZE + 16 # 16 = GCM tag size
class TestEncryptionServiceStreaming:
"""Tests for streaming encryption (for large files)."""
@pytest.fixture
def mock_master_key(self):
"""Generate a valid test master key."""
return base64.urlsafe_b64encode(secrets.token_bytes(32)).decode()
@pytest.fixture
def service_with_key(self, mock_master_key):
"""Create an encryption service with a mock master key."""
with patch('app.services.encryption_service.settings') as mock_settings:
mock_settings.ENCRYPTION_MASTER_KEY = mock_master_key
service = EncryptionService()
yield service
def test_streaming_encrypt_decrypt(self, service_with_key):
"""Test streaming encryption and decryption."""
# Create test content
original_content = b"Test content for streaming encryption. " * 1000
file_obj = BytesIO(original_content)
key = service_with_key.generate_key()
# Encrypt using streaming
encrypted_chunks = list(service_with_key.encrypt_file_streaming(file_obj, key))
encrypted_content = b''.join(encrypted_chunks)
# Decrypt using streaming
encrypted_file = BytesIO(encrypted_content)
decrypted_chunks = list(service_with_key.decrypt_file_streaming(encrypted_file, key))
decrypted_content = b''.join(decrypted_chunks)
assert decrypted_content == original_content
class TestEncryptionKeyValidation:
"""Tests for encryption key validation in config."""
def test_valid_master_key(self):
"""Test that a valid master key passes validation."""
from app.core.config import Settings
valid_key = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode()
# This should not raise
with patch.dict('os.environ', {
'JWT_SECRET_KEY': 'test-secret-key-that-is-valid',
'ENCRYPTION_MASTER_KEY': valid_key
}):
settings = Settings()
assert settings.ENCRYPTION_MASTER_KEY == valid_key
def test_invalid_master_key_length(self):
"""Test that an invalid length master key fails validation."""
from app.core.config import Settings
# 16 bytes instead of 32
invalid_key = base64.urlsafe_b64encode(secrets.token_bytes(16)).decode()
with patch.dict('os.environ', {
'JWT_SECRET_KEY': 'test-secret-key-that-is-valid',
'ENCRYPTION_MASTER_KEY': invalid_key
}):
with pytest.raises(ValueError, match="must be a base64-encoded 32-byte key"):
Settings()
def test_invalid_master_key_format(self):
"""Test that an invalid format master key fails validation."""
from app.core.config import Settings
from pydantic import ValidationError
invalid_key = "not-valid-base64!@#$"
with patch.dict('os.environ', {
'JWT_SECRET_KEY': 'test-secret-key-that-is-valid',
'ENCRYPTION_MASTER_KEY': invalid_key
}):
with pytest.raises(ValidationError, match="ENCRYPTION_MASTER_KEY"):
Settings()
def test_empty_master_key_allowed(self):
"""Test that empty master key is allowed (encryption disabled)."""
from app.core.config import Settings
with patch.dict('os.environ', {
'JWT_SECRET_KEY': 'test-secret-key-that-is-valid',
'ENCRYPTION_MASTER_KEY': ''
}):
settings = Settings()
assert settings.ENCRYPTION_MASTER_KEY is None

File diff suppressed because it is too large Load Diff

View File

@@ -114,3 +114,383 @@ class TestSubtaskDepth:
"""Test that MAX_SUBTASK_DEPTH is defined."""
from app.api.tasks.router import MAX_SUBTASK_DEPTH
assert MAX_SUBTASK_DEPTH == 2
class TestDateRangeFilter:
"""Test date range filter for calendar view."""
def test_due_after_filter(self, client, db, admin_token):
"""Test filtering tasks with due_date >= due_after."""
from datetime import datetime, timedelta
from app.models import Space, Project, Task, TaskStatus
# Create test data
space = Space(
id="test-space-id",
name="Test Space",
owner_id="00000000-0000-0000-0000-000000000001",
)
db.add(space)
project = Project(
id="test-project-id",
space_id="test-space-id",
title="Test Project",
owner_id="00000000-0000-0000-0000-000000000001",
security_level="public",
)
db.add(project)
status = TaskStatus(
id="test-status-id",
project_id="test-project-id",
name="To Do",
color="#808080",
position=0,
)
db.add(status)
# Create tasks with different due dates
now = datetime.now()
task1 = Task(
id="task-1",
project_id="test-project-id",
title="Task Due Yesterday",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id",
due_date=now - timedelta(days=1),
)
task2 = Task(
id="task-2",
project_id="test-project-id",
title="Task Due Today",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id",
due_date=now,
)
task3 = Task(
id="task-3",
project_id="test-project-id",
title="Task Due Tomorrow",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id",
due_date=now + timedelta(days=1),
)
task4 = Task(
id="task-4",
project_id="test-project-id",
title="Task No Due Date",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id",
due_date=None,
)
db.add_all([task1, task2, task3, task4])
db.commit()
# Filter tasks due today or later
due_after = now.isoformat()
response = client.get(
f"/api/projects/test-project-id/tasks?due_after={due_after}",
headers={"Authorization": f"Bearer {admin_token}"},
)
assert response.status_code == 200
data = response.json()
# Should return task2 and task3 (due today and tomorrow)
assert data["total"] == 2
task_ids = [t["id"] for t in data["tasks"]]
assert "task-2" in task_ids
assert "task-3" in task_ids
assert "task-1" not in task_ids
assert "task-4" not in task_ids
def test_due_before_filter(self, client, db, admin_token):
"""Test filtering tasks with due_date <= due_before."""
from datetime import datetime, timedelta
from app.models import Space, Project, Task, TaskStatus
# Create test data
space = Space(
id="test-space-id-2",
name="Test Space 2",
owner_id="00000000-0000-0000-0000-000000000001",
)
db.add(space)
project = Project(
id="test-project-id-2",
space_id="test-space-id-2",
title="Test Project 2",
owner_id="00000000-0000-0000-0000-000000000001",
security_level="public",
)
db.add(project)
status = TaskStatus(
id="test-status-id-2",
project_id="test-project-id-2",
name="To Do",
color="#808080",
position=0,
)
db.add(status)
# Create tasks with different due dates
now = datetime.now()
task1 = Task(
id="task-b-1",
project_id="test-project-id-2",
title="Task Due Yesterday",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id-2",
due_date=now - timedelta(days=1),
)
task2 = Task(
id="task-b-2",
project_id="test-project-id-2",
title="Task Due Today",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id-2",
due_date=now,
)
task3 = Task(
id="task-b-3",
project_id="test-project-id-2",
title="Task Due Tomorrow",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id-2",
due_date=now + timedelta(days=1),
)
db.add_all([task1, task2, task3])
db.commit()
# Filter tasks due today or earlier
due_before = now.isoformat()
response = client.get(
f"/api/projects/test-project-id-2/tasks?due_before={due_before}",
headers={"Authorization": f"Bearer {admin_token}"},
)
assert response.status_code == 200
data = response.json()
# Should return task1 and task2 (due yesterday and today)
assert data["total"] == 2
task_ids = [t["id"] for t in data["tasks"]]
assert "task-b-1" in task_ids
assert "task-b-2" in task_ids
assert "task-b-3" not in task_ids
def test_date_range_filter_combined(self, client, db, admin_token):
"""Test filtering tasks within a date range (due_after AND due_before)."""
from datetime import datetime, timedelta
from app.models import Space, Project, Task, TaskStatus
# Create test data
space = Space(
id="test-space-id-3",
name="Test Space 3",
owner_id="00000000-0000-0000-0000-000000000001",
)
db.add(space)
project = Project(
id="test-project-id-3",
space_id="test-space-id-3",
title="Test Project 3",
owner_id="00000000-0000-0000-0000-000000000001",
security_level="public",
)
db.add(project)
status = TaskStatus(
id="test-status-id-3",
project_id="test-project-id-3",
name="To Do",
color="#808080",
position=0,
)
db.add(status)
# Create tasks spanning a week
now = datetime.now()
start_of_week = now - timedelta(days=now.weekday()) # Monday
end_of_week = start_of_week + timedelta(days=6) # Sunday
task_before = Task(
id="task-c-before",
project_id="test-project-id-3",
title="Task Before Week",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id-3",
due_date=start_of_week - timedelta(days=1),
)
task_in_week = Task(
id="task-c-in-week",
project_id="test-project-id-3",
title="Task In Week",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id-3",
due_date=start_of_week + timedelta(days=3),
)
task_after = Task(
id="task-c-after",
project_id="test-project-id-3",
title="Task After Week",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id-3",
due_date=end_of_week + timedelta(days=1),
)
db.add_all([task_before, task_in_week, task_after])
db.commit()
# Filter tasks within this week
due_after = start_of_week.isoformat()
due_before = end_of_week.isoformat()
response = client.get(
f"/api/projects/test-project-id-3/tasks?due_after={due_after}&due_before={due_before}",
headers={"Authorization": f"Bearer {admin_token}"},
)
assert response.status_code == 200
data = response.json()
# Should only return the task in the week
assert data["total"] == 1
assert data["tasks"][0]["id"] == "task-c-in-week"
def test_date_filter_with_no_due_date(self, client, db, admin_token):
"""Test that tasks without due_date are excluded from date range filters."""
from datetime import datetime, timedelta
from app.models import Space, Project, Task, TaskStatus
# Create test data
space = Space(
id="test-space-id-4",
name="Test Space 4",
owner_id="00000000-0000-0000-0000-000000000001",
)
db.add(space)
project = Project(
id="test-project-id-4",
space_id="test-space-id-4",
title="Test Project 4",
owner_id="00000000-0000-0000-0000-000000000001",
security_level="public",
)
db.add(project)
status = TaskStatus(
id="test-status-id-4",
project_id="test-project-id-4",
name="To Do",
color="#808080",
position=0,
)
db.add(status)
# Create tasks - some with due_date, some without
now = datetime.now()
task_with_date = Task(
id="task-d-with-date",
project_id="test-project-id-4",
title="Task With Due Date",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id-4",
due_date=now,
)
task_without_date = Task(
id="task-d-without-date",
project_id="test-project-id-4",
title="Task Without Due Date",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id-4",
due_date=None,
)
db.add_all([task_with_date, task_without_date])
db.commit()
# When using date filter, tasks without due_date should be excluded
due_after = (now - timedelta(days=1)).isoformat()
due_before = (now + timedelta(days=1)).isoformat()
response = client.get(
f"/api/projects/test-project-id-4/tasks?due_after={due_after}&due_before={due_before}",
headers={"Authorization": f"Bearer {admin_token}"},
)
assert response.status_code == 200
data = response.json()
# Should only return the task with due_date
assert data["total"] == 1
assert data["tasks"][0]["id"] == "task-d-with-date"
def test_date_filter_backward_compatibility(self, client, db, admin_token):
"""Test that not providing date filters returns all tasks (backward compatibility)."""
from datetime import datetime, timedelta
from app.models import Space, Project, Task, TaskStatus
# Create test data
space = Space(
id="test-space-id-5",
name="Test Space 5",
owner_id="00000000-0000-0000-0000-000000000001",
)
db.add(space)
project = Project(
id="test-project-id-5",
space_id="test-space-id-5",
title="Test Project 5",
owner_id="00000000-0000-0000-0000-000000000001",
security_level="public",
)
db.add(project)
status = TaskStatus(
id="test-status-id-5",
project_id="test-project-id-5",
name="To Do",
color="#808080",
position=0,
)
db.add(status)
# Create tasks with and without due dates
now = datetime.now()
task1 = Task(
id="task-e-1",
project_id="test-project-id-5",
title="Task 1",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id-5",
due_date=now,
)
task2 = Task(
id="task-e-2",
project_id="test-project-id-5",
title="Task 2",
priority="medium",
created_by="00000000-0000-0000-0000-000000000001",
status_id="test-status-id-5",
due_date=None,
)
db.add_all([task1, task2])
db.commit()
# Request without date filters - should return all tasks
response = client.get(
"/api/projects/test-project-id-5/tasks",
headers={"Authorization": f"Bearer {admin_token}"},
)
assert response.status_code == 200
data = response.json()
# Should return both tasks
assert data["total"] == 2