devkitx 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,388 @@
1
+ """Input validation utilities for DevKitX.
2
+
3
+ This module provides utilities for data validation, schema checking,
4
+ and input sanitization.
5
+ """
6
+
7
+ from typing import Any, Callable
8
+
9
+ __all__ = [
10
+ "validate_schema",
11
+ "validate_range",
12
+ "validate_length",
13
+ "validate_regex",
14
+ "validate_json_schema",
15
+ "Validator",
16
+ ]
17
+
18
+
19
+ def validate_schema(data: dict[str, Any], schema: dict[str, type]) -> list[str]:
20
+ """Validate data against type schema.
21
+
22
+ Args:
23
+ data: Data to validate
24
+ schema: Schema defining expected types
25
+
26
+ Returns:
27
+ List of validation error messages
28
+
29
+ Example:
30
+ >>> schema = {"name": str, "age": int, "active": bool}
31
+ >>> data = {"name": "John", "age": 30, "active": True}
32
+ >>> validate_schema(data, schema)
33
+ []
34
+ >>> data = {"name": "John", "age": "30", "active": True}
35
+ >>> validate_schema(data, schema)
36
+ ['Field "age": expected int, got str']
37
+ """
38
+ errors = []
39
+
40
+ # Check for missing required fields
41
+ for field, expected_type in schema.items():
42
+ if field not in data:
43
+ errors.append(f'Missing required field "{field}"')
44
+ continue
45
+
46
+ # Check type
47
+ value = data[field]
48
+ if not isinstance(value, expected_type):
49
+ actual_type = type(value).__name__
50
+ expected_type_name = expected_type.__name__
51
+ errors.append(f'Field "{field}": expected {expected_type_name}, got {actual_type}')
52
+
53
+ return errors
54
+
55
+
56
+ def validate_range(value: int | float, min_val: int | float, max_val: int | float) -> bool:
57
+ """Validate that value is within specified range.
58
+
59
+ Args:
60
+ value: Value to validate
61
+ min_val: Minimum allowed value
62
+ max_val: Maximum allowed value
63
+
64
+ Returns:
65
+ True if value is in range, False otherwise
66
+
67
+ Example:
68
+ >>> validate_range(5, 1, 10)
69
+ True
70
+ >>> validate_range(15, 1, 10)
71
+ False
72
+ >>> validate_range(0, 1, 10)
73
+ False
74
+ """
75
+ if not isinstance(value, (int, float)):
76
+ return False
77
+
78
+ if not isinstance(min_val, (int, float)) or not isinstance(max_val, (int, float)):
79
+ return False
80
+
81
+ if min_val > max_val:
82
+ return False
83
+
84
+ return min_val <= value <= max_val
85
+
86
+
87
+ def validate_length(text: str, min_len: int = 0, max_len: int | None = None) -> bool:
88
+ """Validate text length.
89
+
90
+ Args:
91
+ text: Text to validate
92
+ min_len: Minimum length
93
+ max_len: Maximum length (None for no limit)
94
+
95
+ Returns:
96
+ True if length is valid, False otherwise
97
+
98
+ Example:
99
+ >>> validate_length("hello", 3, 10)
100
+ True
101
+ >>> validate_length("hi", 3, 10)
102
+ False
103
+ >>> validate_length("hello world!", 3, 10)
104
+ False
105
+ >>> validate_length("hello", 3) # No max limit
106
+ True
107
+ """
108
+ if not isinstance(text, str):
109
+ return False
110
+
111
+ if not isinstance(min_len, int) or min_len < 0:
112
+ return False
113
+
114
+ if max_len is not None and (not isinstance(max_len, int) or max_len < 0):
115
+ return False
116
+
117
+ if max_len is not None and min_len > max_len:
118
+ return False
119
+
120
+ text_len = len(text)
121
+
122
+ if text_len < min_len:
123
+ return False
124
+
125
+ if max_len is not None and text_len > max_len:
126
+ return False
127
+
128
+ return True
129
+
130
+
131
+ def validate_regex(text: str, pattern: str) -> bool:
132
+ """Validate text against regex pattern.
133
+
134
+ Args:
135
+ text: Text to validate
136
+ pattern: Regex pattern
137
+
138
+ Returns:
139
+ True if text matches pattern, False otherwise
140
+
141
+ Example:
142
+ >>> validate_regex("hello123", r"^[a-z]+\\d+$")
143
+ True
144
+ >>> validate_regex("Hello123", r"^[a-z]+\\d+$")
145
+ False
146
+ >>> validate_regex("test@example.com", r"^[^@]+@[^@]+\\.[^@]+$")
147
+ True
148
+ """
149
+ import re
150
+
151
+ if not isinstance(text, str) or not isinstance(pattern, str):
152
+ return False
153
+
154
+ try:
155
+ return bool(re.match(pattern, text))
156
+ except re.error:
157
+ # Invalid regex pattern
158
+ return False
159
+
160
+
161
+ def validate_json_schema(data: Any, schema: dict[str, Any]) -> list[str]:
162
+ """Validate data against JSON schema.
163
+
164
+ This is a basic JSON schema validator that supports common validation rules.
165
+
166
+ Args:
167
+ data: Data to validate
168
+ schema: JSON schema with validation rules
169
+
170
+ Returns:
171
+ List of validation error messages
172
+
173
+ Example:
174
+ >>> schema = {
175
+ ... "type": "object",
176
+ ... "properties": {
177
+ ... "name": {"type": "string", "minLength": 1},
178
+ ... "age": {"type": "integer", "minimum": 0}
179
+ ... },
180
+ ... "required": ["name"]
181
+ ... }
182
+ >>> validate_json_schema({"name": "John", "age": 30}, schema)
183
+ []
184
+ >>> validate_json_schema({"age": 30}, schema)
185
+ ['Missing required property: name']
186
+ """
187
+ errors = []
188
+
189
+ def _validate_type(value: Any, expected_type: str, path: str = "") -> None:
190
+ type_map = {
191
+ "string": str,
192
+ "integer": int,
193
+ "number": (int, float),
194
+ "boolean": bool,
195
+ "array": list,
196
+ "object": dict,
197
+ "null": type(None),
198
+ }
199
+
200
+ if expected_type not in type_map:
201
+ errors.append(f"Unknown type '{expected_type}' at {path or 'root'}")
202
+ return
203
+
204
+ expected_python_type = type_map[expected_type]
205
+ if not isinstance(value, expected_python_type):
206
+ actual_type = type(value).__name__
207
+ errors.append(f"Expected {expected_type}, got {actual_type} at {path or 'root'}")
208
+
209
+ def _validate_object(obj: Any, obj_schema: dict[str, Any], path: str = "") -> None:
210
+ if not isinstance(obj, dict):
211
+ return
212
+
213
+ # Check required properties
214
+ required = obj_schema.get("required", [])
215
+ for prop in required:
216
+ if prop not in obj:
217
+ errors.append(f"Missing required property: {prop}")
218
+
219
+ # Validate properties
220
+ properties = obj_schema.get("properties", {})
221
+ for prop, prop_schema in properties.items():
222
+ if prop in obj:
223
+ prop_path = f"{path}.{prop}" if path else prop
224
+ _validate_value(obj[prop], prop_schema, prop_path)
225
+
226
+ def _validate_array(arr: Any, arr_schema: dict[str, Any], path: str = "") -> None:
227
+ if not isinstance(arr, list):
228
+ return
229
+
230
+ # Check array length constraints
231
+ if "minItems" in arr_schema and len(arr) < arr_schema["minItems"]:
232
+ errors.append(
233
+ f"Array too short at {path or 'root'}: minimum {arr_schema['minItems']} items"
234
+ )
235
+
236
+ if "maxItems" in arr_schema and len(arr) > arr_schema["maxItems"]:
237
+ errors.append(
238
+ f"Array too long at {path or 'root'}: maximum {arr_schema['maxItems']} items"
239
+ )
240
+
241
+ # Validate items
242
+ if "items" in arr_schema:
243
+ item_schema = arr_schema["items"]
244
+ for i, item in enumerate(arr):
245
+ item_path = f"{path}[{i}]" if path else f"[{i}]"
246
+ _validate_value(item, item_schema, item_path)
247
+
248
+ def _validate_string(value: Any, str_schema: dict[str, Any], path: str = "") -> None:
249
+ if not isinstance(value, str):
250
+ return
251
+
252
+ if "minLength" in str_schema and len(value) < str_schema["minLength"]:
253
+ errors.append(
254
+ f"String too short at {path or 'root'}: minimum {str_schema['minLength']} characters"
255
+ )
256
+
257
+ if "maxLength" in str_schema and len(value) > str_schema["maxLength"]:
258
+ errors.append(
259
+ f"String too long at {path or 'root'}: maximum {str_schema['maxLength']} characters"
260
+ )
261
+
262
+ if "pattern" in str_schema:
263
+ import re
264
+
265
+ try:
266
+ if not re.match(str_schema["pattern"], value):
267
+ errors.append(f"String does not match pattern at {path or 'root'}")
268
+ except re.error:
269
+ errors.append(f"Invalid regex pattern in schema at {path or 'root'}")
270
+
271
+ def _validate_number(value: Any, num_schema: dict[str, Any], path: str = "") -> None:
272
+ if not isinstance(value, (int, float)):
273
+ return
274
+
275
+ if "minimum" in num_schema and value < num_schema["minimum"]:
276
+ errors.append(f"Value too small at {path or 'root'}: minimum {num_schema['minimum']}")
277
+
278
+ if "maximum" in num_schema and value > num_schema["maximum"]:
279
+ errors.append(f"Value too large at {path or 'root'}: maximum {num_schema['maximum']}")
280
+
281
+ def _validate_value(value: Any, value_schema: dict[str, Any], path: str = "") -> None:
282
+ # Validate type
283
+ if "type" in value_schema:
284
+ _validate_type(value, value_schema["type"], path)
285
+
286
+ # Type-specific validations
287
+ if isinstance(value, dict) and value_schema.get("type") == "object":
288
+ _validate_object(value, value_schema, path)
289
+ elif isinstance(value, list) and value_schema.get("type") == "array":
290
+ _validate_array(value, value_schema, path)
291
+ elif isinstance(value, str) and value_schema.get("type") == "string":
292
+ _validate_string(value, value_schema, path)
293
+ elif isinstance(value, (int, float)) and value_schema.get("type") in ("integer", "number"):
294
+ _validate_number(value, value_schema, path)
295
+
296
+ # Start validation
297
+ _validate_value(data, schema)
298
+
299
+ return errors
300
+
301
+
302
+ class Validator:
303
+ """Rule-based validator for complex validation scenarios.
304
+
305
+ Example:
306
+ >>> validator = Validator()
307
+ >>> validator.add_rule("email", lambda x: "@" in str(x), "Invalid email format")
308
+ >>> validator.add_rule("age", lambda x: isinstance(x, int) and x >= 0, "Age must be a non-negative integer")
309
+ >>> errors = validator.validate({"email": "test@example.com", "age": 25})
310
+ >>> len(errors)
311
+ 0
312
+ >>> errors = validator.validate({"email": "invalid", "age": -5})
313
+ >>> len(errors)
314
+ 2
315
+ """
316
+
317
+ def __init__(self) -> None:
318
+ """Initialize validator."""
319
+ self._rules: dict[str, list[tuple[Callable[[Any], bool], str]]] = {}
320
+
321
+ def add_rule(self, field: str, validator: Callable[[Any], bool], message: str) -> None:
322
+ """Add validation rule.
323
+
324
+ Args:
325
+ field: Field name to validate
326
+ validator: Validation function that returns True if valid
327
+ message: Error message if validation fails
328
+ """
329
+ if not isinstance(field, str):
330
+ raise ValueError("Field name must be a string")
331
+
332
+ if not callable(validator):
333
+ raise ValueError("Validator must be callable")
334
+
335
+ if not isinstance(message, str):
336
+ raise ValueError("Message must be a string")
337
+
338
+ if field not in self._rules:
339
+ self._rules[field] = []
340
+
341
+ self._rules[field].append((validator, message))
342
+
343
+ def validate(self, data: dict[str, Any]) -> list[str]:
344
+ """Validate data against all rules.
345
+
346
+ Args:
347
+ data: Data to validate
348
+
349
+ Returns:
350
+ List of validation error messages
351
+ """
352
+ if not isinstance(data, dict):
353
+ return ["Data must be a dictionary"]
354
+
355
+ errors = []
356
+
357
+ for field, rules in self._rules.items():
358
+ value = data.get(field)
359
+
360
+ for validator_func, error_message in rules:
361
+ try:
362
+ if not validator_func(value):
363
+ errors.append(f"{field}: {error_message}")
364
+ except Exception as e:
365
+ errors.append(f"{field}: Validation error - {str(e)}")
366
+
367
+ return errors
368
+
369
+ def clear_rules(self) -> None:
370
+ """Clear all validation rules."""
371
+ self._rules.clear()
372
+
373
+ def remove_field_rules(self, field: str) -> None:
374
+ """Remove all rules for a specific field.
375
+
376
+ Args:
377
+ field: Field name to remove rules for
378
+ """
379
+ if field in self._rules:
380
+ del self._rules[field]
381
+
382
+ def get_fields(self) -> list[str]:
383
+ """Get list of fields that have validation rules.
384
+
385
+ Returns:
386
+ List of field names
387
+ """
388
+ return list(self._rules.keys())