feat(classify): add rule-based document classification engine, task, and API

Implements the classify pipeline step with:
- Classification rules engine (app/utils/classification_rules.py) with
  pre-built categories (invoice, contract, receipt, letter, report,
  bank_statement, tax_document, insurance, payslip) and support for
  filename patterns, content keywords, and metadata matching rules
- Celery task (app/tasks/classify_document.py) that runs as a pipeline step
- CRUD API (app/api/classification_rules.py) for managing custom rules
- ClassificationRuleModel in app/models.py with migration 027
- Updated pipeline step config_schema and stage mapping
- Comprehensive tests for engine, API, and task

Co-authored-by: christianlouis <361235+christianlouis@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2026-03-09 23:38:05 +00:00
parent e6dfa079cc
commit df051e8b81
13 changed files with 1930 additions and 5 deletions
+1
View File
@@ -61,6 +61,7 @@ from app.main import app as fastapi_app # noqa: E402
# Import models to register them with SQLAlchemy Base
from app.models import ( # noqa: F401, E402
ApiToken,
ClassificationRuleModel,
DocumentMetadata,
FileRecord,
Pipeline,
+290
View File
@@ -0,0 +1,290 @@
"""Tests for the classification rules API endpoints.
Covers CRUD operations, validation, and access control for
``/api/classification-rules``.
"""
import pytest
from app.models import ClassificationRuleModel
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_rule(db_session, owner_id="anonymous", **overrides):
"""Insert a ClassificationRuleModel and return it."""
defaults = {
"owner_id": owner_id,
"name": "test_rule",
"category": "invoice",
"rule_type": "filename_pattern",
"pattern": r"(?i)invoice",
"priority": 0,
"case_sensitive": False,
"enabled": True,
}
defaults.update(overrides)
rule = ClassificationRuleModel(**defaults)
db_session.add(rule)
db_session.commit()
db_session.refresh(rule)
return rule
# ---------------------------------------------------------------------------
# Categories & Rule Types endpoints
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestCategoriesEndpoint:
"""Tests for GET /api/classification-rules/categories."""
def test_list_categories(self, client):
"""Should return a dict of built-in categories."""
r = client.get("/api/classification-rules/categories")
assert r.status_code == 200
data = r.json()
assert isinstance(data, dict)
assert "invoice" in data
assert "contract" in data
assert "receipt" in data
assert "unknown" in data
@pytest.mark.unit
class TestRuleTypesEndpoint:
"""Tests for GET /api/classification-rules/rule-types."""
def test_list_rule_types(self, client):
"""Should return a list of valid rule types."""
r = client.get("/api/classification-rules/rule-types")
assert r.status_code == 200
data = r.json()
assert isinstance(data, list)
assert len(data) == 3
type_values = {item["type"] for item in data}
assert "filename_pattern" in type_values
assert "content_keyword" in type_values
assert "metadata_match" in type_values
# ---------------------------------------------------------------------------
# CRUD Operations
# ---------------------------------------------------------------------------
@pytest.mark.integration
class TestClassificationRuleCRUD:
"""Full CRUD test-suite for classification rules."""
def test_list_rules_empty(self, client):
"""List returns an empty array when no rules exist."""
r = client.get("/api/classification-rules/")
assert r.status_code == 200
assert r.json() == []
def test_create_rule(self, client):
"""POST should create a new classification rule."""
r = client.post(
"/api/classification-rules/",
json={
"name": "My Invoice Rule",
"category": "invoice",
"rule_type": "filename_pattern",
"pattern": r"(?i)rechnung",
"priority": 10,
},
)
assert r.status_code == 201
data = r.json()
assert data["name"] == "My Invoice Rule"
assert data["category"] == "invoice"
assert data["rule_type"] == "filename_pattern"
assert data["priority"] == 10
assert data["enabled"] is True
assert data["id"] is not None
def test_create_rule_invalid_type_rejected(self, client):
"""Creating a rule with an invalid rule_type should be rejected."""
r = client.post(
"/api/classification-rules/",
json={
"name": "Bad Rule",
"category": "test",
"rule_type": "invalid_type",
"pattern": "test",
},
)
assert r.status_code == 400
def test_create_duplicate_name_rejected(self, client):
"""Creating two rules with the same name should be rejected."""
payload = {
"name": "Dupe Rule",
"category": "invoice",
"rule_type": "filename_pattern",
"pattern": "test",
}
r1 = client.post("/api/classification-rules/", json=payload)
assert r1.status_code == 201
r2 = client.post("/api/classification-rules/", json=payload)
assert r2.status_code == 409
def test_get_rule(self, client):
"""GET should return a specific rule by ID."""
create_resp = client.post(
"/api/classification-rules/",
json={
"name": "Get Test Rule",
"category": "contract",
"rule_type": "content_keyword",
"pattern": "agreement|terms",
},
)
rule_id = create_resp.json()["id"]
r = client.get(f"/api/classification-rules/{rule_id}")
assert r.status_code == 200
assert r.json()["name"] == "Get Test Rule"
assert r.json()["category"] == "contract"
def test_get_nonexistent_rule(self, client):
"""GET for a nonexistent rule should return 404."""
r = client.get("/api/classification-rules/99999")
assert r.status_code == 404
def test_update_rule(self, client):
"""PUT should update an existing rule."""
create_resp = client.post(
"/api/classification-rules/",
json={
"name": "Update Test",
"category": "receipt",
"rule_type": "filename_pattern",
"pattern": "receipt",
},
)
rule_id = create_resp.json()["id"]
r = client.put(
f"/api/classification-rules/{rule_id}",
json={"category": "invoice", "priority": 50},
)
assert r.status_code == 200
assert r.json()["category"] == "invoice"
assert r.json()["priority"] == 50
# Name should be unchanged
assert r.json()["name"] == "Update Test"
def test_update_nonexistent_rule(self, client):
"""PUT for a nonexistent rule should return 404."""
r = client.put("/api/classification-rules/99999", json={"category": "test"})
assert r.status_code == 404
def test_update_invalid_rule_type_rejected(self, client):
"""PUT with an invalid rule_type should be rejected."""
create_resp = client.post(
"/api/classification-rules/",
json={
"name": "Invalid Update",
"category": "test",
"rule_type": "filename_pattern",
"pattern": "test",
},
)
rule_id = create_resp.json()["id"]
r = client.put(
f"/api/classification-rules/{rule_id}",
json={"rule_type": "bad_type"},
)
assert r.status_code == 400
def test_delete_rule(self, client):
"""DELETE should remove the rule."""
create_resp = client.post(
"/api/classification-rules/",
json={
"name": "Delete Test",
"category": "test",
"rule_type": "content_keyword",
"pattern": "test",
},
)
rule_id = create_resp.json()["id"]
r = client.delete(f"/api/classification-rules/{rule_id}")
assert r.status_code == 204
# Verify it's gone
r2 = client.get(f"/api/classification-rules/{rule_id}")
assert r2.status_code == 404
def test_delete_nonexistent_rule(self, client):
"""DELETE for a nonexistent rule should return 404."""
r = client.delete("/api/classification-rules/99999")
assert r.status_code == 404
def test_list_rules_after_create(self, client):
"""List should return created rules."""
client.post(
"/api/classification-rules/",
json={
"name": "List Rule 1",
"category": "invoice",
"rule_type": "filename_pattern",
"pattern": "test1",
},
)
client.post(
"/api/classification-rules/",
json={
"name": "List Rule 2",
"category": "contract",
"rule_type": "content_keyword",
"pattern": "test2",
},
)
r = client.get("/api/classification-rules/")
assert r.status_code == 200
assert len(r.json()) == 2
def test_create_rule_with_all_fields(self, client):
"""Create a rule providing all optional fields."""
r = client.post(
"/api/classification-rules/",
json={
"name": "Full Rule",
"category": "tax_document",
"rule_type": "metadata_match",
"pattern": "department=finance",
"priority": 100,
"case_sensitive": True,
"enabled": False,
},
)
assert r.status_code == 201
data = r.json()
assert data["case_sensitive"] is True
assert data["enabled"] is False
assert data["priority"] == 100
def test_create_rule_defaults(self, client):
"""Create a rule with minimal fields to test defaults."""
r = client.post(
"/api/classification-rules/",
json={
"name": "Minimal Rule",
"category": "invoice",
"rule_type": "filename_pattern",
"pattern": "test",
},
)
assert r.status_code == 201
data = r.json()
assert data["priority"] == 0
assert data["case_sensitive"] is False
assert data["enabled"] is True
+422
View File
@@ -0,0 +1,422 @@
"""Tests for the rule-based document classification engine.
Covers the classification engine logic in ``app/utils/classification_rules.py``:
built-in rules, custom rules, confidence scoring, and edge cases.
"""
import pytest
from app.utils.classification_rules import (
BUILTIN_CATEGORIES,
BUILTIN_RULES,
RULE_TYPE_CONTENT,
RULE_TYPE_FILENAME,
RULE_TYPE_METADATA,
ClassificationResult,
ClassificationRule,
MatchedRule,
classify_document,
db_rule_to_engine_rule,
)
# ---------------------------------------------------------------------------
# Built-in categories & rules smoke tests
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestBuiltinCategories:
"""Verify the pre-built categories and rules are sane."""
def test_builtin_categories_not_empty(self):
"""There must be at least one built-in category."""
assert len(BUILTIN_CATEGORIES) > 0
def test_unknown_category_exists(self):
"""The 'unknown' fallback category must be present."""
assert "unknown" in BUILTIN_CATEGORIES
def test_core_categories_present(self):
"""Invoice, contract, and receipt categories must exist."""
for cat in ("invoice", "contract", "receipt"):
assert cat in BUILTIN_CATEGORIES, f"Missing built-in category: {cat}"
def test_builtin_rules_not_empty(self):
"""There must be at least one built-in rule."""
assert len(BUILTIN_RULES) > 0
def test_all_builtin_rules_reference_valid_types(self):
"""Every built-in rule must use a valid rule_type."""
valid_types = {RULE_TYPE_FILENAME, RULE_TYPE_CONTENT, RULE_TYPE_METADATA}
for rule in BUILTIN_RULES:
assert rule.rule_type in valid_types, f"Rule {rule.name!r} has invalid type {rule.rule_type!r}"
# ---------------------------------------------------------------------------
# ClassificationRule dataclass validation
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestClassificationRuleValidation:
"""Test ClassificationRule dataclass validation."""
def test_valid_rule_types(self):
"""Valid rule types should not raise."""
for rt in (RULE_TYPE_FILENAME, RULE_TYPE_CONTENT, RULE_TYPE_METADATA):
rule = ClassificationRule(name="test", category="test", rule_type=rt, pattern="test")
assert rule.rule_type == rt
def test_invalid_rule_type_raises(self):
"""An invalid rule_type should raise ValueError."""
with pytest.raises(ValueError, match="Invalid rule_type"):
ClassificationRule(name="test", category="test", rule_type="invalid", pattern="test")
# ---------------------------------------------------------------------------
# Filename pattern matching
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestFilenamePatternMatching:
"""Test classification via filename patterns."""
def test_invoice_filename(self):
"""A filename containing 'invoice' should classify as invoice."""
result = classify_document(filename="2024-03-01_Invoice_Acme.pdf")
assert result.category == "invoice"
assert result.confidence > 0
def test_german_invoice_filename(self):
"""A filename containing 'Rechnung' should classify as invoice."""
result = classify_document(filename="Rechnung_2024.pdf")
assert result.category == "invoice"
assert result.confidence > 0
def test_contract_filename(self):
"""A filename containing 'contract' should classify as contract."""
result = classify_document(filename="Service_Contract_2024.pdf")
assert result.category == "contract"
def test_receipt_filename(self):
"""A filename containing 'receipt' should classify as receipt."""
result = classify_document(filename="Payment_Receipt.pdf")
assert result.category == "receipt"
def test_unrecognised_filename(self):
"""A generic filename with no keywords should return 'unknown'."""
result = classify_document(filename="document_12345.pdf")
assert result.category == "unknown"
assert result.confidence == 0
def test_empty_filename(self):
"""An empty filename should not match any rule."""
result = classify_document(filename="")
assert result.category == "unknown"
# ---------------------------------------------------------------------------
# Content keyword matching
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestContentKeywordMatching:
"""Test classification via content keywords."""
def test_invoice_content(self):
"""Text containing 'invoice number' should classify as invoice."""
result = classify_document(text="Please pay the invoice number 12345. Amount due: $500")
assert result.category == "invoice"
assert result.confidence > 0
def test_contract_content(self):
"""Text containing 'terms and conditions' should classify as contract."""
result = classify_document(text="The parties hereby agree to the following terms and conditions.")
assert result.category == "contract"
def test_receipt_content(self):
"""Text containing 'payment received' should classify as receipt."""
result = classify_document(text="Thank you. Payment received for order #789.")
assert result.category == "receipt"
def test_bank_statement_content(self):
"""Text containing 'account statement' should classify as bank_statement."""
result = classify_document(text="Monthly account statement. Opening balance: $1,000.")
assert result.category == "bank_statement"
def test_empty_text(self):
"""Empty text should not match any content rule."""
result = classify_document(text="")
assert result.category == "unknown"
def test_case_insensitive_matching(self):
"""Content matching should be case-insensitive by default."""
result = classify_document(text="INVOICE NUMBER 12345")
assert result.category == "invoice"
# ---------------------------------------------------------------------------
# Metadata matching
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestMetadataMatching:
"""Test classification via metadata field matching."""
def test_document_type_invoice(self):
"""metadata document_type=Invoice should classify as invoice."""
result = classify_document(metadata={"document_type": "Invoice"})
assert result.category == "invoice"
assert result.confidence >= 90
def test_document_type_contract(self):
"""metadata document_type=Contract should classify as contract."""
result = classify_document(metadata={"document_type": "Contract"})
assert result.category == "contract"
def test_kommunikationsart_rechnung(self):
"""German classification metadata should classify as invoice."""
result = classify_document(metadata={"kommunikationsart": "Rechnung"})
assert result.category == "invoice"
def test_no_metadata(self):
"""None metadata should not match."""
result = classify_document(metadata=None)
assert result.category == "unknown"
def test_empty_metadata(self):
"""Empty metadata dict should not match."""
result = classify_document(metadata={})
assert result.category == "unknown"
def test_metadata_case_insensitive(self):
"""Metadata matching should be case-insensitive by default."""
result = classify_document(metadata={"document_type": "invoice"})
assert result.category == "invoice"
# ---------------------------------------------------------------------------
# Combined matching / confidence boosting
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestCombinedMatching:
"""Test that multiple matching rules boost confidence."""
def test_filename_and_content_boost(self):
"""Filename + content matching should produce higher confidence than either alone."""
filename_only = classify_document(filename="Invoice_2024.pdf")
combined = classify_document(filename="Invoice_2024.pdf", text="Invoice number: 12345. Amount due: $500.")
assert combined.confidence >= filename_only.confidence
assert len(combined.matched_rules) > len(filename_only.matched_rules)
def test_all_three_signals(self):
"""Filename + content + metadata should produce highest confidence."""
result = classify_document(
filename="Invoice_Acme.pdf",
text="Invoice number: 12345. Amount due: $500.",
metadata={"document_type": "Invoice"},
)
assert result.category == "invoice"
assert result.confidence >= 90
def test_conflicting_signals_most_matches_wins(self):
"""When filename says 'invoice' but content says 'contract', most matches wins."""
result = classify_document(
filename="Invoice.pdf",
text="The parties hereby agree to the following terms and conditions. "
"This agreement between Company A and Company B is effective immediately.",
)
# Content has more keyword matches for contract, but filename matches invoice.
# Either is acceptable as long as the result is deterministic.
assert result.category in ("invoice", "contract")
# ---------------------------------------------------------------------------
# Custom rules
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestCustomRules:
"""Test user-defined custom classification rules."""
def test_custom_rule_matches(self):
"""A custom filename rule should match when pattern hits."""
custom = [
ClassificationRule(
name="custom_hr_doc",
category="hr_document",
rule_type=RULE_TYPE_FILENAME,
pattern=r"(?i)employee|hiring|hr",
)
]
result = classify_document(filename="Employee_Handbook.pdf", custom_rules=custom)
assert result.category == "hr_document"
def test_custom_content_rule(self):
"""A custom content keyword rule should match."""
custom = [
ClassificationRule(
name="custom_medical",
category="medical",
rule_type=RULE_TYPE_CONTENT,
pattern="diagnosis|prescription|patient record",
)
]
result = classify_document(text="Patient record for Jane Doe. Diagnosis: common cold.", custom_rules=custom)
assert result.category == "medical"
def test_custom_metadata_rule(self):
"""A custom metadata rule should match."""
custom = [
ClassificationRule(
name="custom_legal",
category="legal",
rule_type=RULE_TYPE_METADATA,
pattern="department=legal",
)
]
result = classify_document(metadata={"department": "legal"}, custom_rules=custom)
assert result.category == "legal"
def test_custom_rule_overrides_builtin(self):
"""Custom rules with more matches should override built-in rules."""
custom = [
ClassificationRule(
name="custom_internal_invoice",
category="internal_invoice",
rule_type=RULE_TYPE_FILENAME,
pattern=r"(?i)invoice",
priority=100,
),
ClassificationRule(
name="custom_internal_invoice_content",
category="internal_invoice",
rule_type=RULE_TYPE_CONTENT,
pattern="invoice number",
priority=100,
),
]
result = classify_document(
filename="Invoice_2024.pdf",
text="Invoice number: 12345",
custom_rules=custom,
)
# Both builtin and custom rules for "invoice" patterns match, but custom
# has "internal_invoice" as category. The category with more total matches wins.
assert result.category in ("invoice", "internal_invoice")
assert result.confidence > 0
# ---------------------------------------------------------------------------
# db_rule_to_engine_rule converter
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestDbRuleConversion:
"""Test the database model to engine rule converter."""
def test_converts_basic_fields(self):
"""All basic fields should be mapped correctly."""
class FakeDbRule:
name = "test_rule"
category = "invoice"
rule_type = RULE_TYPE_FILENAME
pattern = r"(?i)invoice"
priority = 10
case_sensitive = True
engine_rule = db_rule_to_engine_rule(FakeDbRule())
assert engine_rule.name == "test_rule"
assert engine_rule.category == "invoice"
assert engine_rule.rule_type == RULE_TYPE_FILENAME
assert engine_rule.pattern == r"(?i)invoice"
assert engine_rule.priority == 10
assert engine_rule.case_sensitive is True
def test_defaults_case_sensitive_to_false(self):
"""When case_sensitive is missing, default to False."""
class FakeDbRule:
name = "test"
category = "test"
rule_type = RULE_TYPE_CONTENT
pattern = "test"
priority = 0
engine_rule = db_rule_to_engine_rule(FakeDbRule())
assert engine_rule.case_sensitive is False
# ---------------------------------------------------------------------------
# ClassificationResult
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestClassificationResult:
"""Test the ClassificationResult dataclass."""
def test_default_matched_rules(self):
"""matched_rules should default to an empty list."""
result = ClassificationResult(category="test", confidence=50)
assert result.matched_rules == []
def test_with_matched_rules(self):
"""matched_rules should be populated when provided."""
match = MatchedRule(rule_name="test", rule_type=RULE_TYPE_FILENAME, category="invoice", confidence=60)
result = ClassificationResult(category="invoice", confidence=60, matched_rules=[match])
assert len(result.matched_rules) == 1
assert result.matched_rules[0].rule_name == "test"
# ---------------------------------------------------------------------------
# Edge cases
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestEdgeCases:
"""Test edge cases in the classification engine."""
def test_no_inputs_at_all(self):
"""No filename, text, or metadata should return 'unknown'."""
result = classify_document()
assert result.category == "unknown"
assert result.confidence == 0
assert result.matched_rules == []
def test_metadata_pattern_without_equals(self):
"""A metadata pattern without '=' should not match."""
custom = [
ClassificationRule(
name="bad_pattern",
category="test",
rule_type=RULE_TYPE_METADATA,
pattern="no_equals_sign",
)
]
result = classify_document(metadata={"no_equals_sign": "value"}, custom_rules=custom)
assert result.category == "unknown"
def test_confidence_capped_at_100(self):
"""Confidence should never exceed 100."""
# Create many rules that all match to test the cap
custom = [
ClassificationRule(
name=f"flood_{i}",
category="flood",
rule_type=RULE_TYPE_CONTENT,
pattern="test keyword",
)
for i in range(20)
]
result = classify_document(text="test keyword is here", custom_rules=custom)
assert result.confidence <= 100
+232
View File
@@ -0,0 +1,232 @@
"""Tests for the classify_document Celery task.
Covers the ``classify_document_task`` in ``app/tasks/classify_document.py``.
"""
import json
from unittest.mock import MagicMock, patch
import pytest
from app.models import ClassificationRuleModel, FileRecord
from app.tasks.classify_document import _load_custom_rules
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_file_record(db_session, **overrides):
"""Insert a minimal FileRecord and return it."""
defaults = {
"owner_id": "test-user",
"filehash": "abc123",
"original_filename": "Invoice_2024.pdf",
"local_filename": "/tmp/test.pdf",
"file_size": 1024,
"mime_type": "application/pdf",
"ocr_text": "Invoice number: 12345. Amount due: $500.",
"ai_metadata": None,
}
defaults.update(overrides)
fr = FileRecord(**defaults)
db_session.add(fr)
db_session.commit()
db_session.refresh(fr)
return fr
def _make_rule(db_session, **overrides):
"""Insert a ClassificationRuleModel and return it."""
defaults = {
"owner_id": None,
"name": "test_rule",
"category": "test_category",
"rule_type": "filename_pattern",
"pattern": r"(?i)test",
"priority": 0,
"case_sensitive": False,
"enabled": True,
}
defaults.update(overrides)
rule = ClassificationRuleModel(**defaults)
db_session.add(rule)
db_session.commit()
db_session.refresh(rule)
return rule
# ---------------------------------------------------------------------------
# _load_custom_rules
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestLoadCustomRules:
"""Test the custom rule loading helper."""
@patch("app.tasks.classify_document.SessionLocal")
def test_loads_enabled_rules(self, mock_session_local):
"""Should load enabled rules from the database."""
mock_rule = MagicMock()
mock_rule.name = "rule1"
mock_rule.category = "invoice"
mock_rule.rule_type = "filename_pattern"
mock_rule.pattern = r"(?i)invoice"
mock_rule.priority = 10
mock_rule.case_sensitive = False
mock_db = MagicMock()
mock_query = MagicMock()
mock_db.query.return_value = mock_query
mock_query.filter.return_value = mock_query
mock_query.order_by.return_value = mock_query
mock_query.all.return_value = [mock_rule]
mock_session_local.return_value.__enter__ = MagicMock(return_value=mock_db)
mock_session_local.return_value.__exit__ = MagicMock(return_value=False)
rules = _load_custom_rules(owner_id="test-user")
assert len(rules) == 1
assert rules[0].name == "rule1"
assert rules[0].category == "invoice"
# ---------------------------------------------------------------------------
# classify_document_task (integration-style with mocked DB and Celery)
# ---------------------------------------------------------------------------
@pytest.mark.unit
class TestClassifyDocumentTask:
"""Test the Celery classify_document_task."""
@patch("app.tasks.classify_document.log_task_progress")
@patch("app.tasks.classify_document._load_custom_rules", return_value=[])
@patch("app.tasks.classify_document.SessionLocal")
def test_classify_invoice_file(self, mock_session_local, mock_load_rules, mock_log):
"""Should classify a file with invoice filename and text as 'invoice'."""
mock_file = MagicMock(spec=FileRecord)
mock_file.id = 1
mock_file.original_filename = "Invoice_2024.pdf"
mock_file.ocr_text = "Invoice number: 12345. Amount due: $500."
mock_file.ai_metadata = None
mock_file.owner_id = "test-user"
mock_db = MagicMock()
mock_db.query.return_value.filter.return_value.first.return_value = mock_file
mock_session_local.return_value.__enter__ = MagicMock(return_value=mock_db)
mock_session_local.return_value.__exit__ = MagicMock(return_value=False)
from app.tasks.classify_document import classify_document_task
# Call the underlying function directly via .run(), bypassing Celery
result = classify_document_task.run(1, owner_id="test-user")
assert result["status"] == "success"
assert result["category"] == "invoice"
assert result["confidence"] > 0
# Verify ai_metadata was updated
assert mock_file.ai_metadata is not None
metadata = json.loads(mock_file.ai_metadata)
assert "classification" in metadata
assert metadata["classification"]["category"] == "invoice"
@patch("app.tasks.classify_document.log_task_progress")
@patch("app.tasks.classify_document.SessionLocal")
def test_classify_file_not_found(self, mock_session_local, mock_log):
"""Should return error when file record is not found."""
mock_db = MagicMock()
mock_db.query.return_value.filter.return_value.first.return_value = None
mock_session_local.return_value.__enter__ = MagicMock(return_value=mock_db)
mock_session_local.return_value.__exit__ = MagicMock(return_value=False)
from app.tasks.classify_document import classify_document_task
result = classify_document_task.run(99999)
assert result["status"] == "error"
@patch("app.tasks.classify_document.log_task_progress")
@patch("app.tasks.classify_document._load_custom_rules", return_value=[])
@patch("app.tasks.classify_document.SessionLocal")
def test_classify_preserves_existing_metadata(self, mock_session_local, mock_load_rules, mock_log):
"""Should preserve existing ai_metadata fields and add classification."""
existing_meta = json.dumps({"document_type": "Invoice", "tags": ["finance"]})
mock_file = MagicMock(spec=FileRecord)
mock_file.id = 2
mock_file.original_filename = "doc.pdf"
mock_file.ocr_text = ""
mock_file.ai_metadata = existing_meta
mock_file.owner_id = "test-user"
mock_db = MagicMock()
mock_db.query.return_value.filter.return_value.first.return_value = mock_file
mock_session_local.return_value.__enter__ = MagicMock(return_value=mock_db)
mock_session_local.return_value.__exit__ = MagicMock(return_value=False)
from app.tasks.classify_document import classify_document_task
classify_document_task.run(2)
# Check that existing fields are preserved
metadata = json.loads(mock_file.ai_metadata)
assert metadata["tags"] == ["finance"]
assert metadata["document_type"] == "Invoice"
assert "classification" in metadata
@patch("app.tasks.classify_document.log_task_progress")
@patch("app.tasks.classify_document._load_custom_rules", return_value=[])
@patch("app.tasks.classify_document.SessionLocal")
def test_classify_sets_document_type_when_missing(self, mock_session_local, mock_load_rules, mock_log):
"""Should set document_type from classification when not already present."""
mock_file = MagicMock(spec=FileRecord)
mock_file.id = 3
mock_file.original_filename = "Invoice_2024.pdf"
mock_file.ocr_text = "Invoice number: 12345"
mock_file.ai_metadata = json.dumps({"tags": ["test"]})
mock_file.owner_id = "test-user"
mock_db = MagicMock()
mock_db.query.return_value.filter.return_value.first.return_value = mock_file
mock_session_local.return_value.__enter__ = MagicMock(return_value=mock_db)
mock_session_local.return_value.__exit__ = MagicMock(return_value=False)
from app.tasks.classify_document import classify_document_task
classify_document_task.run(3)
metadata = json.loads(mock_file.ai_metadata)
assert metadata["document_type"] == "Invoice"
@patch("app.tasks.classify_document.log_task_progress")
@patch("app.tasks.classify_document._load_custom_rules", return_value=[])
@patch("app.tasks.classify_document.SessionLocal")
def test_classify_unknown_document(self, mock_session_local, mock_load_rules, mock_log):
"""Should classify as 'unknown' when no rules match."""
mock_file = MagicMock(spec=FileRecord)
mock_file.id = 4
mock_file.original_filename = "random_file.pdf"
mock_file.ocr_text = "Lorem ipsum dolor sit amet."
mock_file.ai_metadata = None
mock_file.owner_id = "test-user"
mock_db = MagicMock()
mock_db.query.return_value.filter.return_value.first.return_value = mock_file
mock_session_local.return_value.__enter__ = MagicMock(return_value=mock_db)
mock_session_local.return_value.__exit__ = MagicMock(return_value=False)
from app.tasks.classify_document import classify_document_task
result = classify_document_task.run(4)
assert result["category"] == "unknown"
assert result["confidence"] == 0
def test_classify_document_task_is_celery_task(self):
"""Task should be registered as a Celery task."""
from app.tasks.classify_document import classify_document_task
assert hasattr(classify_document_task, "apply_async")
assert hasattr(classify_document_task, "delay")
assert callable(classify_document_task)