def test_dump(inputs: Sequence[Tuple[Optional[str], str]], value): """Test creating import lines.""" imports = Imports() imports.append( [Import(from_=from_, import_=import_) for from_, import_ in inputs]) assert imports.dump() == value
def parse( self, with_import: Optional[bool] = True, format_: Optional[bool] = True ) -> Union[str, Dict[Tuple[str, ...], str]]: for obj_name, raw_obj in self.base_parser.specification['components'][ 'schemas'].items(): # type: str, Dict obj = JsonSchemaObject.parse_obj(raw_obj) if obj.is_object: self.parse_object(obj_name, obj) elif obj.is_array: self.parse_array(obj_name, obj) elif obj.enum: self.parse_enum(obj_name, obj) elif obj.allOf: self.parse_all_of(obj_name, obj) else: self.parse_root_type(obj_name, obj) if with_import: if self.target_python_version == PythonVersion.PY_37: self.imports.append(IMPORT_ANNOTATIONS) _, sorted_data_models, require_update_action_models = sort_data_models( self.results) results: Dict[Tuple[str, ...], str] = {} module_key = lambda x: (*x.name.split('.')[:-1], ) grouped_models = groupby(sorted(sorted_data_models.values(), key=module_key), key=module_key) for module, models in ((k, [*v]) for k, v in grouped_models): module_path = '.'.join(module) result: List[str] = [] imports = Imports() models_to_update: List[str] = [] for model in models: if model.name in require_update_action_models: models_to_update += [model.name] imports.append(model.imports) for ref_name in model.reference_classes: if '.' not in ref_name: continue ref_path = ref_name.rsplit('.', 1)[0] if ref_path == module_path: continue imports.append(Import(from_='.', import_=ref_path)) if with_import: result += [imports.dump(), self.imports.dump(), '\n'] code = dump_templates(models) result += [code] if self.dump_resolve_reference_action is not None: result += [ '\n', self.dump_resolve_reference_action(models_to_update) ] body = '\n'.join(result) if format_: body = format_code(body, self.target_python_version) if module: module = (*module[:-1], f'{module[-1]}.py') parent = (*module[:-1], '__init__.py') if parent not in results: results[parent] = '' else: module = ('__init__.py', ) results[module] = body # retain existing behaviour if [*results] == [('__init__.py', )]: return results[('__init__.py', )] return results
def dump_imports(self) -> str: imports = Imports() imports.append(self.imports) return imports.dump()