PK!R~fistro/__init__.py__version__ = '0.1.0' PK!Xfistro/config.pyfrom datetime import datetime, date from typing import FrozenSet, List, Dict INT_LENGTH = 9 STR_LENGTH = 9 INT_LIST_LENGTH = 5 MIN_YEAR = 0 MAX_YEAR = 2200 MIN_MONTH = 1 MAX_MONTH = 12 MIN_DAY = 1 MAX_DAY = 31 MIN_HOUR = 0 MAX_HOUR = 23 MIN_MINUTE = 0 MAX_MINUTE = 59 MIN_SECOND = 1 MAX_SECOND = 59 def supported_types() -> FrozenSet: return frozenset([int, str, datetime, date, List[int], Dict[str, int], dict]) PK!Lk..fistro/exceptions.pyclass NotSupportedType(Exception): pass PK!8Š fistro/factory.pyimport builtins from inspect import signature from typing import Type, Callable, List from fistro.config import supported_types from fistro.exceptions import NotSupportedType from fistro.generators import default_generators from fistro.utils import ( is_list, get_base_type, is_dict, get_name, get_return_type, get_return_type_name, ) def builtin_types() -> List: return [ getattr(builtins, d) for d in dir(builtins) if isinstance(getattr(builtins, d), type) ] class Factory: def __init__(self, generators: List[Callable] = default_generators()) -> None: for generator in generators: try: type_name = get_return_type_name(generator) setattr(self, f'{type_name}_generator', generator) except AttributeError: if is_dict(signature(generator).return_annotation): setattr( self, f'{get_base_type(get_return_type(generator))}_dict_generator', generator, ) elif is_list(signature(generator).return_annotation): setattr( self, f'{get_base_type(get_return_type(generator))}_list_generator', generator, ) def factory(self, the_type: Type) -> Callable: if the_type in supported_types(): try: return getattr(self, f'{get_name(the_type)}_generator') except AttributeError: # this is to protect against the case of any type generator is not provided or is a complex type: List... if is_dict(the_type): return getattr(self, f'{get_base_type(the_type)}_dict_generator') elif is_list(the_type): return getattr(self, f'{get_base_type(the_type)}_list_generator') return getattr( DefaultFactory(), f'{get_name(the_type)}_generator' ) # generator for this type is not setup raise NotSupportedType(f'Type {the_type} is not supported') class DefaultFactory: def __init__(self): for generator in default_generators(): type_name = get_return_type_name(generator) setattr(self, f'{type_name}_generator', generator) PK! fistro/fistro.pyimport json from dataclasses import make_dataclass, field, asdict, fields, MISSING from typing import Optional, List, Callable, Any, Union, Dict, Tuple from fistro.factory import Factory from fistro.utils import valid_id def generate( a_class: Any, generators: Optional[List[Callable]] = None, as_dict: bool = False, as_json: bool = False, ) -> Any: # really Union[Type[Any], str, Dict[Any, Any]] but mypy is complaining rich_fields = enrich_fields(a_class, generators) dataclass = make_dataclass(a_class.__name__, rich_fields) if as_dict: return asdict( dataclass() ) # to make asdict parameter must be an instance of dataclass if as_json: return json.dumps(asdict(dataclass())) return dataclass def enrich_fields(a_class, generators) -> List[Tuple[str, type, field]]: return [ ( a_field.name, a_field.type, field( default_factory=Factory().factory(a_field.type) if not generators else Factory(generators).factory(a_field.type) ) if a_field.default is MISSING else field(default=a_field.default), ) for a_field in fields(a_class) ] def generate_from_json(object: Union[Dict[str, Any], List]): if isinstance(object, dict): return make_dataclass( valid_id(), [(key, *inner_inspection(value)) for key, value in object.items()], ) raise NotImplemented('This case makes no much sense') def inner_inspection(inner_object: Any): if isinstance(inner_object, dict): a_key = next(iter(inner_object.keys())) a_value = inner_object[a_key] inner_type = Dict[type(a_key), type(a_value)] elif isinstance(inner_object, list): inner_type = List[type(inner_object[0])] else: inner_type = type(inner_object) # using default factory we can reuse the field and auto-generate similar objects, # with default derived objects would be with this field constant return inner_type, field(default_factory=lambda: inner_object) PK!fl fistro/generators.pyimport string from datetime import datetime, date from random import randint, choices from typing import Dict, Optional, Callable, List from fistro.config import ( MIN_YEAR, MAX_YEAR, MIN_MONTH, MAX_MONTH, MIN_DAY, MAX_DAY, MIN_HOUR, MAX_HOUR, MIN_MINUTE, MAX_MINUTE, MIN_SECOND, MAX_SECOND, STR_LENGTH, INT_LENGTH, INT_LIST_LENGTH, ) # Name is not important, the important thing is the return type # if this one is repeated generator will be override def int_generator(length: int = INT_LENGTH) -> int: return randint(0, 9 * 10 ** length) def str_generator(population: str = string.printable, length: int = STR_LENGTH) -> str: return ''.join(choices(population, k=length)) def datetime_generator(rand_date: Optional[Dict[str, int]] = None) -> datetime: if not rand_date: rand_date = {} min_year = rand_date.get('min_year', MIN_YEAR) max_year = rand_date.get('max_year', MAX_YEAR) min_month = rand_date.get('min_month', MIN_MONTH) max_month = rand_date.get('max_month', MAX_MONTH) min_day = rand_date.get('min_day', MIN_DAY) max_day = rand_date.get('max_day', MAX_DAY) min_hour = rand_date.get('min_hour', MIN_HOUR) max_hour = rand_date.get('max_hour', MAX_HOUR) min_minute = rand_date.get('min_minute', MIN_MINUTE) max_minute = rand_date.get('max_minute', MAX_MINUTE) min_second = rand_date.get('min_second', MIN_SECOND) max_second = rand_date.get('max_second', MAX_SECOND) year = randint(min_year, max_year) month = randint(min_month, max_month) day = randint(min_day, max_day) hour = randint(min_hour, max_hour) minute = randint(min_minute, max_minute) second = randint(min_second, max_second) the_date = datetime( year=year, month=month, day=day, hour=hour, minute=minute, second=second ) return datetime.strptime(str(the_date), '%Y-%m-%d %H:%M:%S') def date_generator(rand_date: Optional[Dict[str, int]] = None) -> date: if not rand_date: rand_date = {} min_year = rand_date.get('min_year', MIN_YEAR) max_year = rand_date.get('max_year', MAX_YEAR) min_month = rand_date.get('min_month', MIN_MONTH) max_month = rand_date.get('max_month', MAX_MONTH) min_day = rand_date.get('min_day', MIN_DAY) max_day = rand_date.get('max_day', MAX_DAY) year = randint(min_year, max_year) month = randint(min_month, max_month) day = randint(min_day, max_day) the_date = date(year=year, month=month, day=day) return datetime.strptime(str(the_date), '%Y-%m-%d').date() def int_list_generator( list_length: int = INT_LIST_LENGTH, int_length: int = INT_LENGTH ) -> List[int]: return [randint(0, 9 * 10 ** int_length) for n in range(list_length)] def int_dict_generator( dict_length: int = INT_LIST_LENGTH, int_length: int = INT_LENGTH ) -> Dict[str, int]: return { str_generator(): randint(0, 9 * 10 ** int_length) for n in range(dict_length) } def default_generators() -> List[Callable]: return [ int_generator, str_generator, datetime_generator, date_generator, int_list_generator, int_dict_generator, ] PK!zHfistro/utils.pyimport string from dataclasses import make_dataclass from inspect import signature from typing import Type, Any, List, Tuple, Optional, Callable from fistro.generators import str_generator def is_list(type: Any) -> bool: try: return type._name == 'List' or type is list except AttributeError: return False def is_dict(type: Any) -> bool: try: return type is dict or type._name == 'Dict' except AttributeError: return False def valid_id() -> str: return str_generator(population=string.ascii_lowercase) def spawn_class(class_name: str, fields: List[Tuple[Any, Any, Optional[Any]]]) -> None: the_class = make_dataclass(class_name, fields) globals()[class_name] = the_class return the_class def get_base_type(type: Any) -> Type: if is_dict(type): return type.__args__[1] return type.__args__[0] def get_name(the_type: Type) -> str: return the_type.__qualname__ def get_return_type(generator: Callable) -> Type: return signature(generator).return_annotation def get_return_type_name(generator: Callable) -> str: return_type = signature(generator).return_annotation try: return return_type.__qualname__ except AttributeError: # is a complex type: List or Dict if is_dict(return_type): return f'{get_base_type(return_type)}_dict' elif is_list(return_type): return f'{get_base_type(return_type)}_list' PK!**fistro-0.2.0.dist-info/LICENSE Copyright 2018 Pablo Cabezas Salas Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.PK!HlŃTTfistro-0.2.0.dist-info/WHEEL A н#J@Z|Jmqvh&#hڭw!Ѭ"J˫( } %PK!Hb&fistro-0.2.0.dist-info/METADATAU͎6))`w"6ph,AOJEzUHd͡of- T&|~)a]k-N5ar`$cL=gC+s2\`\b^U1¸FXy]g̋eR1eT{ёOvqndRXe'`ee^ j2wk͎|6W|(ڗSH[ ]µl(a}>Qq&wRkod))5~MϯSlpaU* v|`>f19(]Ps e2YoڪpAAq*مm}W_riu=U}{giۼsb S<'NVikm8Yߡ]dR=|wh8_5.D'( J9GͮmN%CSO^UC^*ПBISFLa%=%@zi C ҕ> [lfБ=7C3 |aӘ E}Ku@[/ T6GӋe=A,0"f0xytSXLG\5ϔFejL>܇(-~Fe,˦f:4U @ c G@6NI >. E#9Ȑ(//ۀ?{eɌlFC};URZgPK!H> &fistro-0.2.0.dist-info/RECORDuɒ@{?Ka,> K ",BYҧ|Y⦭8q<9&Gd'DZWut*IabaJLr?(Hí#уĘ:gs)԰<4x'du7<Oxdŭiެ}CƽWC\.TLqM*P7[$kz|sƑdvJaMgGgG1-5M2ۊ,K;ޠVȈk'>RKN3RSmUX4ǞWv5PA:IIjQc%ztCH]pDǾRu-;ypI %nws]BgR UEtв0W(3z,&ein'_`'HWWIW9H$S&ݷ)"nڹ. Co4uޒbhOP[Wm0>q~ֈ䶙ro*S,rdu?a1b,CH2] Zy'0ﮯ)߾ PK!R~fistro/__init__.pyPK!XGfistro/config.pyPK!Lk..3fistro/exceptions.pyPK!8Š fistro/factory.pyPK! b fistro/fistro.pyPK!fl :fistro/generators.pyPK!zHh"fistro/utils.pyPK!**(fistro-0.2.0.dist-info/LICENSEPK!HlŃTT,fistro-0.2.0.dist-info/WHEELPK!Hb&w-fistro-0.2.0.dist-info/METADATAPK!H> &0fistro-0.2.0.dist-info/RECORDPK 3