Best Python code snippet using localstack_python
scaffold.py
Source:scaffold.py
...26 return True27 if is_keyword(name):28 return True29 return False30def to_valid_python_name(spec_name: str) -> str:31 sanitized = re.sub(r"[^0-9a-zA-Z_]+", "_", spec_name)32 if sanitized[0].isnumeric():33 sanitized = "i_" + sanitized34 if is_keyword(sanitized):35 sanitized += "_"36 if sanitized.startswith("__"):37 sanitized = sanitized[1:]38 return sanitized39class ShapeNode:40 service: ServiceModel41 shape: Shape42 def __init__(self, service: ServiceModel, shape: Shape) -> None:43 super().__init__()44 self.service = service45 self.shape = shape46 @property47 def is_request(self):48 for operation_name in self.service.operation_names:49 operation = self.service.operation_model(operation_name)50 if operation.input_shape is None:51 continue52 if to_valid_python_name(self.shape.name) == to_valid_python_name(53 operation.input_shape.name54 ):55 return True56 return False57 @property58 def name(self) -> str:59 return to_valid_python_name(self.shape.name)60 @property61 def is_exception(self):62 metadata = self.shape.metadata63 return metadata.get("error") or metadata.get("exception")64 @property65 def is_primitive(self):66 return self.shape.type_name in ["integer", "boolean", "float", "double", "string"]67 @property68 def is_enum(self):69 return isinstance(self.shape, StringShape) and self.shape.enum70 @property71 def dependencies(self) -> List[str]:72 shape = self.shape73 if isinstance(shape, StructureShape):74 return [to_valid_python_name(v.name) for v in shape.members.values()]75 if isinstance(shape, ListShape):76 return [to_valid_python_name(shape.member.name)]77 if isinstance(shape, MapShape):78 return [to_valid_python_name(shape.key.name), to_valid_python_name(shape.value.name)]79 return []80 def _print_structure_declaration(self, output, doc=True, quote_types=False):81 if self.is_exception:82 self._print_as_class(output, "ServiceException", doc)83 return84 if any(map(is_keyword, self.shape.members.keys())):85 self._print_as_typed_dict(output)86 return87 if self.is_request:88 base = "ServiceRequest"89 else:90 base = "TypedDict, total=False"91 self._print_as_class(output, base, doc, quote_types)92 def _print_as_class(self, output, base: str, doc=True, quote_types=False):93 output.write(f"class {to_valid_python_name(self.shape.name)}({base}):\n")94 q = '"' if quote_types else ""95 if doc:96 self.print_shape_doc(output, self.shape)97 if not self.shape.members:98 output.write(" pass\n")99 for k, v in self.shape.members.items():100 if k in self.shape.required_members:101 output.write(f" {k}: {q}{to_valid_python_name(v.name)}{q}\n")102 else:103 output.write(f" {k}: Optional[{q}{to_valid_python_name(v.name)}{q}]\n")104 def _print_as_typed_dict(self, output, doc=True, quote_types=False):105 name = to_valid_python_name(self.shape.name)106 q = '"' if quote_types else ""107 output.write('%s = TypedDict("%s", {\n' % (name, name))108 for k, v in self.shape.members.items():109 if k in self.shape.required_members:110 output.write(f' "{k}": {q}{to_valid_python_name(v.name)}{q},\n')111 else:112 output.write(f' "{k}": Optional[{q}{to_valid_python_name(v.name)}{q}],\n')113 output.write("}, total=False)")114 def print_shape_doc(self, output, shape):115 html = shape.documentation116 import pypandoc117 doc = pypandoc.convert_text(html, "rst", format="html")118 rst = doc.strip()119 if rst:120 output.write(' """')121 output.write(f"{doc.strip()}\n")122 output.write(' """\n')123 def print_declaration(self, output, doc=True, quote_types=False):124 shape = self.shape125 q = '"' if quote_types else ""126 if isinstance(shape, StructureShape):127 self._print_structure_declaration(output, doc, quote_types)128 elif isinstance(shape, ListShape):129 output.write(130 f"{to_valid_python_name(shape.name)} = List[{q}{to_valid_python_name(shape.member.name)}{q}]"131 )132 elif isinstance(shape, MapShape):133 output.write(134 f"{to_valid_python_name(shape.name)} = Dict[{q}{to_valid_python_name(shape.key.name)}{q}, {q}{to_valid_python_name(shape.value.name)}{q}]"135 )136 elif isinstance(shape, StringShape):137 if shape.enum:138 output.write(f"class {to_valid_python_name(shape.name)}(str):\n")139 for value in shape.enum:140 name = to_valid_python_name(value)141 output.write(f' {name} = "{value}"\n')142 else:143 output.write(f"{to_valid_python_name(shape.name)} = str")144 elif shape.type_name == "string":145 output.write(f"{to_valid_python_name(shape.name)} = str")146 elif shape.type_name == "integer":147 output.write(f"{to_valid_python_name(shape.name)} = int")148 elif shape.type_name == "long":149 output.write(f"{to_valid_python_name(shape.name)} = int")150 elif shape.type_name == "double":151 output.write(f"{to_valid_python_name(shape.name)} = float")152 elif shape.type_name == "float":153 output.write(f"{to_valid_python_name(shape.name)} = float")154 elif shape.type_name == "boolean":155 output.write(f"{to_valid_python_name(shape.name)} = bool")156 elif shape.type_name == "blob":157 output.write(158 f"{to_valid_python_name(shape.name)} = bytes"159 ) # FIXME check what type blob really is160 elif shape.type_name == "timestamp":161 output.write(f"{to_valid_python_name(shape.name)} = datetime")162 else:163 output.write(164 f"# unknown shape type for {to_valid_python_name(shape.name)}: {shape.type_name}"165 )166 # TODO: BoxedInteger?167 output.write("\n")168 def get_order(self):169 """170 Defines a basic order in which to sort the stack of shape nodes before printing.171 First all non-enum primitives are printed, then enums, then exceptions, then all other types.172 """173 if self.is_primitive:174 if self.is_enum:175 return 1176 else:177 return 0178 if self.is_exception:179 return 2180 return 3181def generate_service_types(output, service: ServiceModel, doc=True):182 output.write("import sys\n")183 output.write("from typing import Dict, List, Optional\n")184 output.write("from datetime import datetime\n")185 output.write("if sys.version_info >= (3, 8):\n")186 output.write(" from typing import TypedDict\n")187 output.write("else:\n")188 output.write(" from typing_extensions import TypedDict\n")189 output.write("\n")190 output.write(191 "from localstack.aws.api import handler, RequestContext, ServiceException, ServiceRequest"192 )193 output.write("\n")194 # ==================================== print type declarations195 nodes: Dict[str, ShapeNode] = {}196 for shape_name in service.shape_names:197 shape = service.shape_for(shape_name)198 nodes[to_valid_python_name(shape_name)] = ShapeNode(service, shape)199 # output.write("__all__ = [\n")200 # for name in nodes.keys():201 # output.write(f' "{name}",\n')202 # output.write("]\n")203 printed: Set[str] = set()204 visited: Set[str] = set()205 stack: List[str] = list(nodes.keys())206 stack = sorted(stack, key=lambda name: nodes[name].get_order())207 stack.reverse()208 while stack:209 name = stack.pop()210 if name in printed:211 continue212 node = nodes[name]213 dependencies = [dep for dep in node.dependencies if dep not in printed]214 if not dependencies:215 node.print_declaration(output, doc=doc)216 printed.add(name)217 elif name in visited:218 # break out of circular dependencies219 node.print_declaration(output, doc=doc, quote_types=True)220 printed.add(name)221 else:222 stack.append(name)223 stack.extend(dependencies)224 visited.add(name)225def generate_service_api(output, service: ServiceModel, doc=True):226 service_name = service.service_name.replace("-", "_")227 class_name = service_name + "_api"228 class_name = snake_to_camel_case(class_name)229 output.write(f"class {class_name}:\n")230 output.write("\n")231 output.write(f' service = "{service.service_name}"\n')232 output.write(f' version = "{service.api_version}"\n')233 for op_name in service.operation_names:234 operation: OperationModel = service.operation_model(op_name)235 fn_name = camel_to_snake_case(op_name)236 if operation.output_shape:237 output_shape = to_valid_python_name(operation.output_shape.name)238 else:239 output_shape = "None"240 output.write("\n")241 parameters = OrderedDict()242 param_shapes = OrderedDict()243 input_shape = operation.input_shape244 if input_shape is not None:245 members = list(input_shape.members)246 for m in input_shape.required_members:247 members.remove(m)248 m_shape = input_shape.members[m]249 parameters[xform_name(m)] = to_valid_python_name(m_shape.name)250 param_shapes[xform_name(m)] = m_shape251 for m in members:252 m_shape = input_shape.members[m]253 param_shapes[xform_name(m)] = m_shape254 parameters[xform_name(m)] = f"{to_valid_python_name(m_shape.name)} = None"255 if any(map(is_bad_param_name, parameters.keys())):256 # if we cannot render the parameter name, don't expand the parameters in the handler257 param_list = f"request: {to_valid_python_name(input_shape.name)}" if input_shape else ""258 output.write(f' @handler("{operation.name}", expand=False)\n')259 else:260 param_list = ", ".join([f"{k}: {v}" for k, v in parameters.items()])261 output.write(f' @handler("{operation.name}")\n')262 output.write(263 f" def {fn_name}(self, context: RequestContext, {param_list}) -> {output_shape}:\n"264 )265 # convert html documentation to rst and print it into to the signature266 if doc:267 html = operation.documentation268 import pypandoc269 doc = pypandoc.convert_text(html, "rst", format="html")270 output.write(' """')271 output.write(f"{doc.strip()}\n")272 output.write("\n")273 # parameters274 for param_name, shape in param_shapes.items():275 # FIXME: this doesn't work properly276 pdoc = pypandoc.convert_text(shape.documentation, "rst", format="html")277 pdoc = pdoc.strip().split(".")[0] + "."278 output.write(f":param {param_name}: {pdoc}\n")279 # return value280 if operation.output_shape:281 output.write(f":returns: {to_valid_python_name(operation.output_shape.name)}\n")282 # errors283 for error in operation.error_shapes:284 output.write(f":raises {to_valid_python_name(error.name)}:\n")285 output.write(' """\n')286 output.write(" raise NotImplementedError\n")287@click.group()288def scaffold():289 pass290@scaffold.command(name="generate")291@click.argument("service", type=str)292@click.option("--doc/--no-doc", default=False, help="whether or not to generate docstrings")293@click.option(294 "--save/--print",295 default=False,296 help="whether or not to save the result into the api directory",297)298@click.option(...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!