openforce/tests/phase4/test_sprint41_custom_fields.py
Goose eaaf3f2791 test(phase4): add Sprint 4.1/4.2/4.3 QA gate stubs
Contract tests for:
- 4.1: entity_name/custom_object mutual exclusion, GIN index in migration,
       additionalProperties validation on standard objects, custom field
       transfer during lead conversion
- 4.2: DecisionNode first-match determinism, SubflowNode depth limit (10),
       LoopNode cycle detection, AssignmentNode operators
- 4.3: post_save dispatch, / context, re-entrancy
       guard, Celery Beat idempotency

All tests will fail until Sprint 4.x code lands — intentional.
2026-09-26 17:30:02 +00:00

178 lines
7.7 KiB
Python

"""
Sprint 4.1 QA Gate: Custom __c fields on standard CRM objects.
All tests are contract stubs — they will fail (ImportError or NotImplementedError)
until Goose's Sprint 4.1 code lands. That is intentional.
"""
import pytest
# ---------------------------------------------------------------------------
# 4.1.1 entity_name / custom_object mutual exclusion
# ---------------------------------------------------------------------------
class TestCustomFieldDefinitionEntityConstraint:
"""CustomFieldDefinition must have EITHER custom_object OR entity_name, not both, not neither."""
def test_entity_name_without_custom_object_is_valid(self, db):
"""A field attached to a standard object (entity_name='Account') is valid."""
from custom_objects.models import CustomFieldDefinition
field = CustomFieldDefinition(
name="annual_revenue_tier__c",
label="Annual Revenue Tier",
field_type="text",
entity_name="Account",
)
# Should not raise
field.full_clean()
def test_custom_object_without_entity_name_is_valid(self, db):
"""A field attached to a CustomObjectDefinition is valid."""
from custom_objects.models import CustomObjectDefinition, CustomFieldDefinition
obj = CustomObjectDefinition(name="Project__c", label="Project", plural_label="Projects")
obj.save()
field = CustomFieldDefinition(
name="budget__c",
label="Budget",
field_type="number",
custom_object=obj,
)
field.full_clean()
def test_both_entity_name_and_custom_object_raises(self, db):
"""Setting both entity_name and custom_object must be rejected."""
from django.core.exceptions import ValidationError
from custom_objects.models import CustomObjectDefinition, CustomFieldDefinition
obj = CustomObjectDefinition(name="Project__c", label="Project", plural_label="Projects")
obj.save()
field = CustomFieldDefinition(
name="bad_field__c",
label="Bad Field",
field_type="text",
entity_name="Account",
custom_object=obj,
)
with pytest.raises(ValidationError):
field.full_clean()
def test_neither_entity_name_nor_custom_object_raises(self, db):
"""Setting neither entity_name nor custom_object must be rejected."""
from django.core.exceptions import ValidationError
from custom_objects.models import CustomFieldDefinition
field = CustomFieldDefinition(
name="orphan__c",
label="Orphan",
field_type="text",
)
with pytest.raises(ValidationError):
field.full_clean()
# ---------------------------------------------------------------------------
# 4.1.2 GIN index present in migration (not just model Meta)
# ---------------------------------------------------------------------------
class TestCustomFieldsGINIndex:
"""Verify the GIN index on custom_fields is declared in the migration SQL."""
def test_gin_index_in_migration_sql(self):
"""The migration adding custom_fields must include a GIN index creation."""
import os, re
migration_dir = os.path.join(
os.path.dirname(__file__), '..', '..', 'crm_core', 'migrations'
)
migration_files = sorted(f for f in os.listdir(migration_dir) if f.endswith('.py'))
gin_found = False
for fname in migration_files:
path = os.path.join(migration_dir, fname)
content = open(path).read()
if 'custom_fields' in content and re.search(r'gin|GIN|GinIndex', content):
gin_found = True
break
assert gin_found, (
"No migration found that adds a GIN index on custom_fields. "
"The index must be in the migration, not just model Meta."
)
# ---------------------------------------------------------------------------
# 4.1.3 additionalProperties: False on standard object endpoints
# ---------------------------------------------------------------------------
class TestStandardObjectCustomFieldValidation:
"""Standard object serializers must reject unknown custom_fields keys."""
def test_unknown_custom_field_key_rejected_on_account(self, db):
"""POST to Account with an unknown custom_fields key must return 400."""
from django.contrib.auth.models import User
from rest_framework.test import APIClient
user = User.objects.create_user('qa_user41', password='pass')
client = APIClient()
client.force_authenticate(user=user)
payload = {
'name': 'Acme Corp',
'custom_fields': {'nonexistent_field__c': 'some_value'},
}
response = client.post('/api/accounts/', payload, format='json')
assert response.status_code == 400, (
f"Expected 400 for unknown custom_fields key, got {response.status_code}. "
"additionalProperties: False must be enforced on standard object endpoints."
)
def test_registered_custom_field_accepted_on_account(self, db):
"""POST with a registered __c field must be accepted (201)."""
from django.contrib.auth.models import User
from rest_framework.test import APIClient
from custom_objects.models import CustomFieldDefinition
# Register a custom field for Account
CustomFieldDefinition.objects.create(
name="region__c",
label="Region",
field_type="text",
entity_name="Account",
is_required=False,
)
user = User.objects.create_user('qa_user41b', password='pass')
client = APIClient()
client.force_authenticate(user=user)
payload = {
'name': 'Acme Corp',
'custom_fields': {'region__c': 'EMEA'},
}
response = client.post('/api/accounts/', payload, format='json')
assert response.status_code == 201, (
f"Expected 201 for valid registered custom field, got {response.status_code}."
)
def test_custom_fields_preserved_on_lead_conversion(self, db):
"""Custom __c fields on Lead must transfer to the resulting Contact during conversion."""
from django.contrib.auth.models import User
from rest_framework.test import APIClient
from custom_objects.models import CustomFieldDefinition
CustomFieldDefinition.objects.create(
name="referral_source__c",
label="Referral Source",
field_type="text",
entity_name="Lead",
is_required=False,
)
user = User.objects.create_user('qa_user41c', password='pass')
client = APIClient()
client.force_authenticate(user=user)
# Create lead with custom field
lead_resp = client.post('/api/leads/', {
'first_name': 'Jane',
'last_name': 'Doe',
'email': 'jane@example.com',
'company': 'Acme',
'custom_fields': {'referral_source__c': 'Partner'},
}, format='json')
assert lead_resp.status_code == 201
lead_id = lead_resp.data['id']
# Convert
conv_resp = client.post(f'/api/leads/{lead_id}/convert/', {
'create_opportunity': False,
}, format='json')
assert conv_resp.status_code == 200
# Check Contact has the custom field value
contact_id = conv_resp.data.get('contact_id')
contact_resp = client.get(f'/api/contacts/{contact_id}/')
assert contact_resp.data.get('custom_fields', {}).get('referral_source__c') == 'Partner', (
"custom_fields must transfer from Lead to Contact during conversion."
)