You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_metadata_bug_complete.py 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. from pathlib import Path
  2. from unittest.mock import Mock, create_autospec, patch
  3. import pytest
  4. from flask_restx import reqparse
  5. from werkzeug.exceptions import BadRequest
  6. from models.account import Account
  7. from services.entities.knowledge_entities.knowledge_entities import MetadataArgs
  8. from services.metadata_service import MetadataService
  9. class TestMetadataBugCompleteValidation:
  10. """Complete test suite to verify the metadata nullable bug and its fix."""
  11. def test_1_pydantic_layer_validation(self):
  12. """Test Layer 1: Pydantic model validation correctly rejects None values."""
  13. # Pydantic should reject None values for required fields
  14. with pytest.raises((ValueError, TypeError)):
  15. MetadataArgs(type=None, name=None)
  16. with pytest.raises((ValueError, TypeError)):
  17. MetadataArgs(type="string", name=None)
  18. with pytest.raises((ValueError, TypeError)):
  19. MetadataArgs(type=None, name="test")
  20. # Valid values should work
  21. valid_args = MetadataArgs(type="string", name="test_name")
  22. assert valid_args.type == "string"
  23. assert valid_args.name == "test_name"
  24. def test_2_business_logic_layer_crashes_on_none(self):
  25. """Test Layer 2: Business logic crashes when None values slip through."""
  26. # Create mock that bypasses Pydantic validation
  27. mock_metadata_args = Mock()
  28. mock_metadata_args.name = None
  29. mock_metadata_args.type = "string"
  30. mock_user = create_autospec(Account, instance=True)
  31. mock_user.current_tenant_id = "tenant-123"
  32. mock_user.id = "user-456"
  33. with patch("services.metadata_service.current_user", mock_user):
  34. # Should crash with TypeError
  35. with pytest.raises(TypeError, match="object of type 'NoneType' has no len"):
  36. MetadataService.create_metadata("dataset-123", mock_metadata_args)
  37. # Test update method as well
  38. mock_user = create_autospec(Account, instance=True)
  39. mock_user.current_tenant_id = "tenant-123"
  40. mock_user.id = "user-456"
  41. with patch("services.metadata_service.current_user", mock_user):
  42. with pytest.raises(TypeError, match="object of type 'NoneType' has no len"):
  43. MetadataService.update_metadata_name("dataset-123", "metadata-456", None)
  44. def test_3_database_constraints_verification(self):
  45. """Test Layer 3: Verify database model has nullable=False constraints."""
  46. from sqlalchemy import inspect
  47. from models.dataset import DatasetMetadata
  48. # Get table info
  49. mapper = inspect(DatasetMetadata)
  50. # Check that type and name columns are not nullable
  51. type_column = mapper.columns["type"]
  52. name_column = mapper.columns["name"]
  53. assert type_column.nullable is False, "type column should be nullable=False"
  54. assert name_column.nullable is False, "name column should be nullable=False"
  55. def test_4_fixed_api_layer_rejects_null(self, app):
  56. """Test Layer 4: Fixed API configuration properly rejects null values."""
  57. # Test Console API create endpoint (fixed)
  58. parser = reqparse.RequestParser()
  59. parser.add_argument("type", type=str, required=True, nullable=False, location="json")
  60. parser.add_argument("name", type=str, required=True, nullable=False, location="json")
  61. with app.test_request_context(json={"type": None, "name": None}, content_type="application/json"):
  62. with pytest.raises(BadRequest):
  63. parser.parse_args()
  64. # Test with just name being null
  65. with app.test_request_context(json={"type": "string", "name": None}, content_type="application/json"):
  66. with pytest.raises(BadRequest):
  67. parser.parse_args()
  68. # Test with just type being null
  69. with app.test_request_context(json={"type": None, "name": "test"}, content_type="application/json"):
  70. with pytest.raises(BadRequest):
  71. parser.parse_args()
  72. def test_5_fixed_api_accepts_valid_values(self, app):
  73. """Test that fixed API still accepts valid non-null values."""
  74. parser = reqparse.RequestParser()
  75. parser.add_argument("type", type=str, required=True, nullable=False, location="json")
  76. parser.add_argument("name", type=str, required=True, nullable=False, location="json")
  77. with app.test_request_context(json={"type": "string", "name": "valid_name"}, content_type="application/json"):
  78. args = parser.parse_args()
  79. assert args["type"] == "string"
  80. assert args["name"] == "valid_name"
  81. def test_6_simulated_buggy_behavior(self, app):
  82. """Test simulating the original buggy behavior with nullable=True."""
  83. # Simulate the old buggy configuration
  84. buggy_parser = reqparse.RequestParser()
  85. buggy_parser.add_argument("type", type=str, required=True, nullable=True, location="json")
  86. buggy_parser.add_argument("name", type=str, required=True, nullable=True, location="json")
  87. with app.test_request_context(json={"type": None, "name": None}, content_type="application/json"):
  88. # This would pass in the buggy version
  89. args = buggy_parser.parse_args()
  90. assert args["type"] is None
  91. assert args["name"] is None
  92. # But would crash when trying to create MetadataArgs
  93. with pytest.raises((ValueError, TypeError)):
  94. MetadataArgs(**args)
  95. def test_7_end_to_end_validation_layers(self):
  96. """Test all validation layers work together correctly."""
  97. # Layer 1: API should reject null at parameter level (with fix)
  98. # Layer 2: Pydantic should reject null at model level
  99. # Layer 3: Business logic expects non-null
  100. # Layer 4: Database enforces non-null
  101. # Test that valid data flows through all layers
  102. valid_data = {"type": "string", "name": "test_metadata"}
  103. # Should create valid Pydantic object
  104. metadata_args = MetadataArgs(**valid_data)
  105. assert metadata_args.type == "string"
  106. assert metadata_args.name == "test_metadata"
  107. # Should not crash in business logic length check
  108. assert len(metadata_args.name) <= 255 # This should not crash
  109. assert len(metadata_args.type) > 0 # This should not crash
  110. def test_8_verify_specific_fix_locations(self):
  111. """Verify that the specific locations mentioned in bug report are fixed."""
  112. # Read the actual files to verify fixes
  113. import os
  114. # Console API create
  115. console_create_file = "api/controllers/console/datasets/metadata.py"
  116. if os.path.exists(console_create_file):
  117. content = Path(console_create_file).read_text()
  118. # Should contain nullable=False, not nullable=True
  119. assert "nullable=True" not in content.split("class DatasetMetadataCreateApi")[1].split("class")[0]
  120. # Service API create
  121. service_create_file = "api/controllers/service_api/dataset/metadata.py"
  122. if os.path.exists(service_create_file):
  123. content = Path(service_create_file).read_text()
  124. # Should contain nullable=False, not nullable=True
  125. create_api_section = content.split("class DatasetMetadataCreateServiceApi")[1].split("class")[0]
  126. assert "nullable=True" not in create_api_section
  127. class TestMetadataValidationSummary:
  128. """Summary tests that demonstrate the complete validation architecture."""
  129. def test_validation_layer_architecture(self):
  130. """Document and test the 4-layer validation architecture."""
  131. # Layer 1: API Parameter Validation (Flask-RESTful reqparse)
  132. # - Role: First line of defense, validates HTTP request parameters
  133. # - Fixed: nullable=False ensures null values are rejected at API boundary
  134. # Layer 2: Pydantic Model Validation
  135. # - Role: Validates data structure and types before business logic
  136. # - Working: Required fields without Optional[] reject None values
  137. # Layer 3: Business Logic Validation
  138. # - Role: Domain-specific validation (length checks, uniqueness, etc.)
  139. # - Vulnerable: Direct len() calls crash on None values
  140. # Layer 4: Database Constraints
  141. # - Role: Final data integrity enforcement
  142. # - Working: nullable=False prevents None values in database
  143. # The bug was: Layer 1 allowed None, but Layers 2-4 expected non-None
  144. # The fix: Make Layer 1 consistent with Layers 2-4
  145. assert True # This test documents the architecture
  146. if __name__ == "__main__":
  147. pytest.main([__file__, "-v"])