"""JsonSchema Utils.""" import random from typing import Any import exrex # type: ignore[import-untyped] from factory.fuzzy import FuzzyFloat, FuzzyInteger, FuzzyText MAX_NUM = 999999999999999 MIN_NUM = -MAX_NUM MAX_STRING_LENGTH = 100 MAX_LIST_ITEMS = 100 def get_fake_data(json_schema: dict[str, Any]) -> dict[str, Any]: """Get fake data.""" properties = json_schema["properties"] fake_data = {} for key, value in properties.items(): try: data_type = value["type"] except Exception: pass if isinstance(data_type, list): data_type = random.choice(data_type) fake_data[key] = type_to_generator[data_type](value) # type: ignore[no-untyped-call] return fake_data def _generate_string(schema: dict[str, Any]) -> Any: if "enum" in schema.keys(): return random.choice(schema["enum"]) if "pattern" in schema.keys(): return exrex.getone(schema["pattern"], MAX_STRING_LENGTH) return FuzzyText( length=random.randrange( schema.get("minLength", 0), schema.get("maxLength", MAX_STRING_LENGTH) ) ).fuzz() type_to_generator = { "string": _generate_string, "number": lambda schema: FuzzyFloat( schema.get("minimum", MIN_NUM), schema.get("maximum", MAX_NUM) ).fuzz(), "integer": lambda schema: FuzzyInteger( schema.get("minimum", MIN_NUM), schema.get("maximum", MAX_NUM) ).fuzz(), "null": lambda schema: None, "object": get_fake_data, "array": lambda schema: [ get_fake_data(schema["items"]) for _ in range( random.randrange( schema.get("minItems", 0), schema.get("maxItems", MAX_LIST_ITEMS) ) ) ], "boolean": lambda schema: bool(random.getrandbits(1)), }