Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

test_metadata_bug_complete.py 8.4KB

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