How to use get_token method in Gherkin-python

Best Python code snippet using gherkin-python

parser.py

Source:parser.py Github

copy

Full Screen

...6 self.tokens = tokens7 self.current_token = -18 self.tree = self.create_tree()9 # get next token from token list10 def get_token(self):11 self.current_token += 112 return self.tokens[self.current_token]13 # compare token with expected token14 def compare_tokens(self, token, type, msg=""):15 if token.token_type != type:16 raise SyntaxError(token, msg)17 # get all token parsed and return AST18 def create_tree(self):19 model_description, model_content = self.parse_model()20 model = parser_objects.Model(model_content[0], model_content[1], model_content[2],21 model_content[3], model_description[0], model_description[1])22 return model23 # parse all tokens24 def parse_model(self):25 token = self.get_token()26 self.compare_tokens(token, TokenType.T_LEFT_BRACKET, "Model does not start with '<'")27 token = self.get_token()28 self.compare_tokens(token, TokenType.T_UML_MODEL, "Model not defined")29 model_description = self.parse_model_description() # [id, name]30 token = self.get_token()31 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET, "Model description does not end with '>'")32 model_content = self.parse_model_content() # [file_description, imports, elements, profiles]33 self.parse_model_end()34 return model_description, model_content35 # parse model description36 # model description = 'xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI"37 # xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" ,38 # ['xmlns:notation="http://www.eclipse.org/gmf/runtime/1.0.2/notation"'] ,39 # xmlns:uml="http://www.eclipse.org/uml2/3.0.0/UML" xmlns:umlnotation="http://www.ibm.com/xtools/1.5.3/Umlnotation"40 # xmi:id=', string value, ' name=', string value;41 def parse_model_description(self):42 token = self.get_token()43 self.compare_tokens(token, TokenType.T_XMI_VERSION)44 token = self.get_token()45 self.compare_tokens(token, TokenType.T_EQUALS)46 token = self.get_token()47 self.compare_tokens(token, TokenType.T_STRING_VALUE)48 token = self.get_token()49 self.compare_tokens(token, TokenType.T_XMLNS_XMI)50 token = self.get_token()51 self.compare_tokens(token, TokenType.T_EQUALS)52 token = self.get_token()53 self.compare_tokens(token, TokenType.T_STRING_VALUE)54 token = self.get_token()55 self.compare_tokens(token, TokenType.T_XMLNS_XSI)56 token = self.get_token()57 self.compare_tokens(token, TokenType.T_EQUALS)58 token = self.get_token()59 self.compare_tokens(token, TokenType.T_STRING_VALUE)60 token = self.get_token()61 self.compare_tokens(token, TokenType.T_XMLNS_ECORE)62 token = self.get_token()63 self.compare_tokens(token, TokenType.T_EQUALS)64 token = self.get_token()65 self.compare_tokens(token, TokenType.T_STRING_VALUE)66 token = self.get_token()67 if token.token_type == TokenType.T_XMLNS_NOTATION:68 token = self.get_token()69 self.compare_tokens(token, TokenType.T_EQUALS)70 token = self.get_token()71 self.compare_tokens(token, TokenType.T_STRING_VALUE)72 token = self.get_token()73 self.compare_tokens(token, TokenType.T_XMLNS_UML)74 token = self.get_token()75 self.compare_tokens(token, TokenType.T_EQUALS)76 token = self.get_token()77 self.compare_tokens(token, TokenType.T_STRING_VALUE)78 token = self.get_token()79 self.compare_tokens(token, TokenType.T_XMLNS_UML_NOTATION)80 token = self.get_token()81 self.compare_tokens(token, TokenType.T_EQUALS)82 token = self.get_token()83 self.compare_tokens(token, TokenType.T_STRING_VALUE)84 token = self.get_token()85 self.compare_tokens(token, TokenType.T_XMI_ID)86 token = self.get_token()87 self.compare_tokens(token, TokenType.T_EQUALS)88 token = self.get_token()89 self.compare_tokens(token, TokenType.T_STRING_VALUE)90 # model id91 id = token.value92 token = self.get_token()93 self.compare_tokens(token, TokenType.T_NAME)94 token = self.get_token()95 self.compare_tokens(token, TokenType.T_EQUALS)96 token = self.get_token()97 self.compare_tokens(token, TokenType.T_STRING_VALUE)98 # model name99 name = token.value100 return [id, name]101 # parse everything after model description102 # model contents = file description,{ package import },{ packaged element },{ profile application };103 def parse_model_content(self):104 file_description = self.parse_file_description()105 imports = []106 pckg_import = self.parse_package_import()107 while pckg_import != None:108 imports.append(pckg_import)109 pckg_import = self.parse_package_import()110 elements = []111 pckg_element = self.parse_packaged_element()112 while pckg_element != None:113 elements.append(pckg_element)114 pckg_element = self.parse_packaged_element()115 profiles = []116 profile_application = self.parse_profile_application()117 while profile_application != None:118 profiles.append(profile_application)119 profile_application = self.parse_profile_application()120 return [file_description, imports, elements, profiles]121 # file description = "<eAnnotations xmi:id=", string value, 'source="uml2.diagrams"', ['references=', string value]122 # ,'>', file name, "</eAnnotations>";123 def parse_file_description(self):124 token = self.get_token()125 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)126 token = self.get_token()127 self.compare_tokens(token, TokenType.T_EANNOTATIONS)128 token = self.get_token()129 self.compare_tokens(token, TokenType.T_XMI_ID)130 token = self.get_token()131 self.compare_tokens(token, TokenType.T_EQUALS)132 token = self.get_token()133 self.compare_tokens(token, TokenType.T_STRING_VALUE)134 id = token.value135 token = self.get_token()136 self.compare_tokens(token, TokenType.T_SOURCE)137 token = self.get_token()138 self.compare_tokens(token, TokenType.T_EQUALS)139 token = self.get_token()140 self.compare_tokens(token, TokenType.T_STRING_VALUE)141 source = token.value142 token = self.get_token()143 if token.token_type == TokenType.T_REFERENCES:144 token = self.get_token()145 self.compare_tokens(token, TokenType.T_EQUALS)146 token = self.get_token()147 self.compare_tokens(token, TokenType.T_STRING_VALUE)148 token = self.get_token()149 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)150 graphics = self.parse_file_name()151 file_description = parser_objects.FileDescription(graphics.graphic, id, source)152 return file_description153 # file name = "<contents xmi:type="umlnotation:UMLDiagram" xmi:id=", string value, ' type="Class" name=',154 # string value, ">", graphic description, "</contents>";155 def parse_file_name(self):156 token = self.get_token()157 graphics = parser_objects.GraphicDescription()158 while type(token) is not Token:159 # skip graphic description160 # append all tokens to GraphicDescription class161 graphics.graphic.append(token)162 token = self.get_token()163 self.current_token -= 1164 return graphics165 # package import = "<packageImport xmi:id=", id, ">", package, "</packageImport>";166 def parse_package_import(self):167 token = self.get_token()168 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)169 token = self.get_token()170 if token.token_type == TokenType.T_PACKAGED_ELEMENT:171 self.current_token -= 2172 return None173 self.compare_tokens(token, TokenType.T_PACKAGE_IMPORT)174 token = self.get_token()175 self.compare_tokens(token, TokenType.T_XMI_ID)176 token = self.get_token()177 self.compare_tokens(token, TokenType.T_EQUALS)178 token = self.get_token()179 self.compare_tokens(token, TokenType.T_STRING_VALUE)180 id = token.value181 token = self.get_token()182 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)183 type, href = self.parse_package()184 token = self.get_token()185 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)186 token = self.get_token()187 self.compare_tokens(token, TokenType.T_SLASH)188 token = self.get_token()189 self.compare_tokens(token, TokenType.T_PACKAGE_IMPORT)190 token = self.get_token()191 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)192 package = parser_objects.ImportedPackage(id, type, href)193 return package194 # package = '<importedPackage xmi:type="uml:Model" href=', string value, "/>";195 def parse_package(self):196 token = self.get_token()197 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)198 token = self.get_token()199 self.compare_tokens(token, TokenType.T_IMPORTED_PACKAGE)200 token = self.get_token()201 self.compare_tokens(token, TokenType.T_XMI_TYPE)202 token = self.get_token()203 self.compare_tokens(token, TokenType.T_EQUALS)204 token = self.get_token()205 self.compare_tokens(token, TokenType.T_STRING_VALUE)206 type = token.value207 token = self.get_token()208 self.compare_tokens(token, TokenType.T_HREF)209 token = self.get_token()210 self.compare_tokens(token, TokenType.T_EQUALS)211 token = self.get_token()212 self.compare_tokens(token, TokenType.T_STRING_VALUE)213 href = token.value214 token = self.get_token()215 self.compare_tokens(token, TokenType.T_SLASH)216 token = self.get_token()217 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)218 return type, href219 # packaged element = "<packagedElement xmi:type=", ( class | association ), "</packagedElement>";220 def parse_packaged_element(self):221 token = self.get_token()222 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)223 token = self.get_token()224 if token.token_type != TokenType.T_PACKAGED_ELEMENT:225 self.current_token -= 2226 return None227 self.compare_tokens(token, TokenType.T_PACKAGED_ELEMENT)228 token = self.get_token()229 self.compare_tokens(token, TokenType.T_XMI_TYPE)230 token = self.get_token()231 self.compare_tokens(token, TokenType.T_EQUALS)232 token = self.get_token()233 self.compare_tokens(token, TokenType.T_STRING_VALUE)234 if token.value == '"uml:Class"':235 return self.parse_class()236 elif token.value == '"uml:Association"':237 return self.parse_association()238 else:239 raise SyntaxError(token, "Unrecognised packaged element, xmi:type expected: uml:Class or uml:Association")240 # class = '"uml:Class" xmi:id=', string value, " name=", string value, visibility, ['isLeaf="true"'],241 # ['isAbstract="true"'], ">", [ stereotype ], [ generalization ], {attribute}, {operation};242 def parse_class(self):243 token = self.get_token()244 self.compare_tokens(token, TokenType.T_XMI_ID)245 token = self.get_token()246 self.compare_tokens(token, TokenType.T_EQUALS)247 token = self.get_token()248 self.compare_tokens(token, TokenType.T_STRING_VALUE)249 id = token.value250 token = self.get_token()251 self.compare_tokens(token, TokenType.T_NAME)252 token = self.get_token()253 self.compare_tokens(token, TokenType.T_EQUALS)254 token = self.get_token()255 self.compare_tokens(token, TokenType.T_STRING_VALUE)256 name = token.value257 visibility = self.parse_visibility()258 is_abstract = '"false"'259 is_leaf = '"false"'260 token = self.get_token()261 if token.token_type != TokenType.T_RIGHT_BRACKET or token.token_type != TokenType.T_SLASH:262 while token.token_type == TokenType.T_IS_LEAF or token.token_type == TokenType.T_IS_ABSTRACT:263 option_type = token.token_type264 token = self.get_token()265 self.compare_tokens(token, TokenType.T_EQUALS)266 token = self.get_token()267 self.compare_tokens(token, TokenType.T_STRING_VALUE)268 if token.value != '"true"' and token.value != '"false"':269 raise SyntaxError(token, "Unexpected value, expected true or false value")270 else:271 if option_type == TokenType.T_IS_LEAF:272 is_leaf = token.value273 elif option_type == TokenType.T_IS_ABSTRACT:274 is_abstract = token.value275 token = self.get_token()276 if token.token_type == TokenType.T_SLASH:277 token = self.get_token()278 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)279 parsed_class = parser_objects.Class(id, name, visibility, is_leaf, is_abstract, None, [], [], [])280 return parsed_class281 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)282 stereotype = self.parse_stereotype()283 generalizations = []284 generalization = self.parse_generalization()285 while generalization != None:286 generalizations.append(generalization)287 generalization = self.parse_generalization()288 attributes = []289 attribute = self.parse_attribute()290 while attribute != None:291 attributes.append(attribute)292 attribute = self.parse_attribute()293 operations = []294 operation = self.parse_operation()295 while operation != None:296 operations.append(operation)297 operation = self.parse_operation()298 self.parse_packaged_element_end()299 parsed_class = parser_objects.Class(id, name, visibility, is_leaf, is_abstract, stereotype, generalizations, attributes, operations)300 return parsed_class301 # visibility = " visibility=", visibility type;302 # visibility type = "public" | "private" | "protected" | "package";303 def parse_visibility(self):304 token = self.get_token()305 if token.token_type != TokenType.T_VISIBILITY:306 self.current_token -= 1307 return '"public"'308 self.compare_tokens(token, TokenType.T_VISIBILITY)309 token = self.get_token()310 self.compare_tokens(token, TokenType.T_EQUALS)311 token = self.get_token()312 self.compare_tokens(token, TokenType.T_STRING_VALUE)313 if token.value == '"public"' or token.value == '"private"' or token.value == '"protected"' \314 or token.value == '"package"':315 return token.value316 else:317 raise SyntaxError(token, "Unexpected visibility")318 # stereotype = "<eAnnotations xmi:id=", string value, " source=", string value, ">", stereotype description,319 # {stereotype description}, "</eAnnotations>";320 def parse_stereotype(self):321 token = self.get_token()322 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)323 token = self.get_token()324 if token.token_type != TokenType.T_EANNOTATIONS:325 self.current_token -= 2326 return None327 self.compare_tokens(token, TokenType.T_EANNOTATIONS)328 token = self.get_token()329 self.compare_tokens(token, TokenType.T_XMI_ID)330 token = self.get_token()331 self.compare_tokens(token, TokenType.T_EQUALS)332 token = self.get_token()333 self.compare_tokens(token, TokenType.T_STRING_VALUE)334 id = token.value335 token = self.get_token()336 self.compare_tokens(token, TokenType.T_SOURCE)337 token = self.get_token()338 self.compare_tokens(token, TokenType.T_EQUALS)339 token = self.get_token()340 self.compare_tokens(token, TokenType.T_STRING_VALUE)341 source = token.value342 token = self.get_token()343 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)344 stereotypes = []345 stereotype = self.parse_stereotype_description()346 while stereotype != None:347 stereotypes.append(stereotype)348 stereotype = self.parse_stereotype_description()349 token = self.get_token()350 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)351 token = self.get_token()352 self.compare_tokens(token, TokenType.T_SLASH)353 token = self.get_token()354 self.compare_tokens(token, TokenType.T_EANNOTATIONS)355 token = self.get_token()356 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)357 stereotypes_obj = parser_objects.Stereotype(id, source, stereotypes)358 return stereotypes_obj359 # stereotype description = "<details xmi:id=", string value, " key=", string value, "/>";360 def parse_stereotype_description(self):361 token = self.get_token()362 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)363 token = self.get_token()364 if token.token_type != TokenType.T_DETAILS:365 self.current_token -= 2366 return None367 self.compare_tokens(token, TokenType.T_DETAILS)368 token = self.get_token()369 self.compare_tokens(token, TokenType.T_XMI_ID)370 token = self.get_token()371 self.compare_tokens(token, TokenType.T_EQUALS)372 token = self.get_token()373 self.compare_tokens(token, TokenType.T_STRING_VALUE)374 id = token.value375 token = self.get_token()376 self.compare_tokens(token, TokenType.T_KEY)377 token = self.get_token()378 self.compare_tokens(token, TokenType.T_EQUALS)379 token = self.get_token()380 self.compare_tokens(token, TokenType.T_STRING_VALUE)381 key = token.value382 token = self.get_token()383 self.compare_tokens(token, TokenType.T_SLASH)384 token = self.get_token()385 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)386 return [id, key]387 # generalization = "<generalization xmi:id=", string value, " general=", string value, "/>";388 def parse_generalization(self):389 token = self.get_token()390 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)391 token = self.get_token()392 if token.token_type != TokenType.T_GENERALIZATION:393 self.current_token -= 2394 return None395 self.compare_tokens(token, TokenType.T_GENERALIZATION)396 token = self.get_token()397 self.compare_tokens(token, TokenType.T_XMI_ID)398 token = self.get_token()399 self.compare_tokens(token, TokenType.T_EQUALS)400 token = self.get_token()401 self.compare_tokens(token, TokenType.T_STRING_VALUE)402 id = token.value403 token = self.get_token()404 self.compare_tokens(token, TokenType.T_GENERAL)405 token = self.get_token()406 self.compare_tokens(token, TokenType.T_EQUALS)407 token = self.get_token()408 self.compare_tokens(token, TokenType.T_STRING_VALUE)409 general = token.value410 token = self.get_token()411 self.compare_tokens(token, TokenType.T_SLASH)412 token = self.get_token()413 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)414 generalization = parser_objects.Generalization(id, general)415 return generalization416 # attribute = "<ownedAttribute xmi:id=", string value, " name=", string value, attribute parameters,417 # ( "/>" | attribute description );418 # attribute description = ">", [type], [limit], [default value], "</ownedAttribute>";419 def parse_attribute(self):420 token = self.get_token()421 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)422 token = self.get_token()423 if token.token_type != TokenType.T_OWNED_ATTRIBUTE:424 self.current_token -= 2425 return None426 self.compare_tokens(token, TokenType.T_OWNED_ATTRIBUTE)427 token = self.get_token()428 self.compare_tokens(token, TokenType.T_XMI_ID)429 token = self.get_token()430 self.compare_tokens(token, TokenType.T_EQUALS)431 token = self.get_token()432 self.compare_tokens(token, TokenType.T_STRING_VALUE)433 id = token.value434 token = self.get_token()435 self.compare_tokens(token, TokenType.T_NAME)436 token = self.get_token()437 self.compare_tokens(token, TokenType.T_EQUALS)438 token = self.get_token()439 self.compare_tokens(token, TokenType.T_STRING_VALUE)440 name = token.value441 parameters = self.parse_attribute_parameters()442 token = self.get_token()443 if token.token_type == TokenType.T_SLASH:444 token = self.get_token()445 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)446 attribute = parser_objects.Attribute(id, name, parameters, None, None, None, None)447 return attribute448 elif token.token_type == TokenType.T_RIGHT_BRACKET:449 type = self.parse_type()450 upper_limit = self.parse_upper_limit()451 lower_limit = self.parse_lower_limit()452 default_value = self.parse_default_value()453 if type is None and default_value[1] is not None:454 type = default_value[1]455 token = self.get_token()456 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)457 token = self.get_token()458 self.compare_tokens(token, TokenType.T_SLASH)459 token = self.get_token()460 self.compare_tokens(token, TokenType.T_OWNED_ATTRIBUTE)461 token = self.get_token()462 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)463 attribute = parser_objects.Attribute(id, name, parameters, type, upper_limit, lower_limit, default_value[0])464 return attribute465 else:466 raise SyntaxError(token, "Unexpected OwnedAttribute ending, expected '/' or '>'")467 # type = "<type xmi:type=", string value, "href=", string value,"/>";468 def parse_type(self):469 token = self.get_token()470 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)471 token = self.get_token()472 if token.token_type != TokenType.T_TYPE:473 self.current_token -= 2474 return None475 self.compare_tokens(token, TokenType.T_TYPE)476 token = self.get_token()477 self.compare_tokens(token, TokenType.T_XMI_TYPE)478 token = self.get_token()479 self.compare_tokens(token, TokenType.T_EQUALS)480 token = self.get_token()481 self.compare_tokens(token, TokenType.T_STRING_VALUE)482 type = token.value483 token = self.get_token()484 self.compare_tokens(token, TokenType.T_HREF)485 token = self.get_token()486 self.compare_tokens(token, TokenType.T_EQUALS)487 token = self.get_token()488 self.compare_tokens(token, TokenType.T_STRING_VALUE)489 href = token.value490 token = self.get_token()491 self.compare_tokens(token, TokenType.T_SLASH)492 token = self.get_token()493 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)494 return type, href495 # default value = "<defaultValue xmi:type=", string value, " xmi:id=", string value, " value=", string value,496 # ( default value type | "/>" );497 # default value type = type, "</defaultValue>";498 def parse_default_value(self):499 token = self.get_token()500 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)501 token = self.get_token()502 if token.token_type != TokenType.T_DEFAULT_VALUE:503 self.current_token -= 2504 return [None, None]505 self.compare_tokens(token, TokenType.T_DEFAULT_VALUE)506 token = self.get_token()507 self.compare_tokens(token, TokenType.T_XMI_TYPE)508 token = self.get_token()509 self.compare_tokens(token, TokenType.T_EQUALS)510 token = self.get_token()511 self.compare_tokens(token, TokenType.T_STRING_VALUE)512 type = token.value513 token = self.get_token()514 self.compare_tokens(token, TokenType.T_XMI_ID)515 token = self.get_token()516 self.compare_tokens(token, TokenType.T_EQUALS)517 token = self.get_token()518 self.compare_tokens(token, TokenType.T_STRING_VALUE)519 id = token.value520 token = self.get_token()521 self.compare_tokens(token, TokenType.T_VALUE)522 token = self.get_token()523 self.compare_tokens(token, TokenType.T_EQUALS)524 token = self.get_token()525 self.compare_tokens(token, TokenType.T_STRING_VALUE)526 value = token.value527 token = self.get_token()528 default_type = None529 if token.token_type != TokenType.T_SLASH:530 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)531 default_type = self.parse_type()532 token = self.get_token()533 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)534 token = self.get_token()535 self.compare_tokens(token, TokenType.T_SLASH)536 token = self.get_token()537 self.compare_tokens(token, TokenType.T_DEFAULT_VALUE)538 token = self.get_token()539 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)540 default_value = parser_objects.Limit(type, id, value)541 return [default_value, default_type]542 # attribute parameters = visibility, ['isLeaf="true"'], ['isStatic="true"'], ['isOrdered="true"'],543 # ['isReadOnly="true"'], ['isDerived="true"'], ['isDerivedUnion="true"'], [short type], [association type];544 # association type = [ 'aggregation="composite"' | 'aggregation="shared"' ], "association=", string value;545 def parse_attribute_parameters(self):546 visibility = self.parse_visibility()547 token = self.get_token()548 aggregation = None549 association = None550 type = None551 options = ['"false"', '"false"', '"false"', '"true"', '"false"', '"false"', '"false"']552 if token.token_type != TokenType.T_RIGHT_BRACKET and token.token_type != TokenType.T_SLASH:553 while token.token_type == TokenType.T_IS_LEAF or token.token_type == TokenType.T_IS_STATIC \554 or token.token_type == TokenType.T_IS_ORDERED or token.token_type == TokenType.T_IS_READ_ONLY \555 or token.token_type == TokenType.T_IS_DERIVED or token.token_type == TokenType.T_IS_DERIVED_UNION \556 or token.token_type == TokenType.T_IS_UNIQUE:557 type = token.token_type558 token = self.get_token()559 self.compare_tokens(token, TokenType.T_EQUALS)560 token = self.get_token()561 self.compare_tokens(token, TokenType.T_STRING_VALUE)562 if type == TokenType.T_IS_LEAF:563 options[0] = token.value564 elif type == TokenType.T_IS_STATIC:565 options[1] = token.value566 elif type == TokenType.T_IS_ORDERED:567 options[2] = token.value568 elif type == TokenType.T_IS_UNIQUE:569 options[3] = token.value570 elif type == TokenType.T_IS_READ_ONLY:571 options[4] = token.value572 elif type == TokenType.T_IS_DERIVED:573 options[5] = token.value574 elif type == TokenType.T_IS_DERIVED_UNION:575 options[6] = token.value576 type = None577 token = self.get_token()578 if token.token_type == TokenType.T_TYPE:579 token = self.get_token()580 self.compare_tokens(token, TokenType.T_EQUALS)581 token = self.get_token()582 self.compare_tokens(token, TokenType.T_STRING_VALUE)583 type = token.value584 token = self.get_token()585 if token.token_type == TokenType.T_AGGREGATION:586 token = self.get_token()587 self.compare_tokens(token, TokenType.T_EQUALS)588 token = self.get_token()589 self.compare_tokens(token, TokenType.T_STRING_VALUE)590 aggregation = token.value591 token = self.get_token()592 if token.token_type == TokenType.T_ASSOCIATION:593 token = self.get_token()594 self.compare_tokens(token, TokenType.T_EQUALS)595 token = self.get_token()596 self.compare_tokens(token, TokenType.T_STRING_VALUE)597 association = token.value598 token = self.get_token()599 self.current_token -= 1600 parameters = parser_objects.AttributeParameters(visibility, options[0], options[1], options[2], options[3], options[4], options[5], options[6], aggregation, association, type)601 return parameters602 # operation = "<ownedOperation xmi:id=", string value, " name=", string value, [ operation parameters ],603 # ("/>" | parameter );604 def parse_operation(self):605 token = self.get_token()606 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)607 token = self.get_token()608 if token.token_type != TokenType.T_OWNED_OPERATION:609 self.current_token -= 2610 return None611 self.compare_tokens(token, TokenType.T_OWNED_OPERATION)612 token = self.get_token()613 self.compare_tokens(token, TokenType.T_XMI_ID)614 token = self.get_token()615 self.compare_tokens(token, TokenType.T_EQUALS)616 token = self.get_token()617 self.compare_tokens(token, TokenType.T_STRING_VALUE)618 id = token.value619 token = self.get_token()620 self.compare_tokens(token, TokenType.T_NAME)621 token = self.get_token()622 self.compare_tokens(token, TokenType.T_EQUALS)623 token = self.get_token()624 self.compare_tokens(token, TokenType.T_STRING_VALUE)625 name = token.value626 parameters = self.parse_operation_parameters()627 token = self.get_token()628 owned_parameters = []629 if token.token_type != TokenType.T_SLASH:630 owned_parameter = self.parse_owned_parameter()631 while owned_parameter != None:632 owned_parameters.append(owned_parameter)633 owned_parameter = self.parse_owned_parameter()634 token = self.get_token()635 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)636 token = self.get_token()637 self.compare_tokens(token, TokenType.T_SLASH)638 token = self.get_token()639 self.compare_tokens(token, TokenType.T_OWNED_OPERATION)640 token = self.get_token()641 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)642 operation = parser_objects.Operation(id, name, parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], owned_parameters)643 return operation644 # operation parameters = visibility, ['isLeaf="true"'], ['isStatic="true"'], ['isQuery="true"'];645 def parse_operation_parameters(self):646 visibility = self.parse_visibility()647 isLeaf = '"false"'648 isStatic = '"false"'649 isAbstract = '"false"'650 isQuery = '"false"'651 token = self.get_token()652 while token.token_type == TokenType.T_IS_LEAF or token.token_type == TokenType.T_IS_STATIC \653 or token.token_type == TokenType.T_IS_QUERY or token.token_type == TokenType.T_IS_ABSTRACT:654 type = token.token_type655 token = self.get_token()656 self.compare_tokens(token, TokenType.T_EQUALS)657 token = self.get_token()658 self.compare_tokens(token, TokenType.T_STRING_VALUE)659 if type == TokenType.T_IS_LEAF:660 isLeaf = token.value661 elif type == TokenType.T_IS_STATIC:662 isStatic = token.value663 elif type == TokenType.T_IS_QUERY:664 isQuery = token.value665 elif type == TokenType.T_IS_ABSTRACT:666 isAbstract = token.value667 token = self.get_token()668 self.current_token -= 1669 return [visibility, isLeaf, isStatic, isAbstract, isQuery]670 # parameter = owned parameter, {owned parameter}, "</ownedOperation>";671 # owned parameter = "<ownedParameter xmi:id=", string value, " name=", string value, [owned parameter parameters],672 # ("/>" | owned parameter description);673 # owned parameter parameters = short type, ['isOrdered="true"'], ['isUnique="false"'], [parameter direction];674 def parse_owned_parameter(self):675 token = self.get_token()676 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)677 token = self.get_token()678 if token.token_type != TokenType.T_OWNED_PARAMETER:679 self.current_token -= 2680 return None681 self.compare_tokens(token, TokenType.T_OWNED_PARAMETER)682 token = self.get_token()683 self.compare_tokens(token, TokenType.T_XMI_ID)684 token = self.get_token()685 self.compare_tokens(token, TokenType.T_EQUALS)686 token = self.get_token()687 self.compare_tokens(token, TokenType.T_STRING_VALUE)688 id = token.value689 token = self.get_token()690 self.compare_tokens(token, TokenType.T_NAME)691 token = self.get_token()692 self.compare_tokens(token, TokenType.T_EQUALS)693 token = self.get_token()694 self.compare_tokens(token, TokenType.T_STRING_VALUE)695 name = token.value696 short_type = self.parse_short_type()697 token = self.get_token()698 isOrdered = '"false"'699 isUnique = '"true"'700 while token.token_type == TokenType.T_IS_ORDERED or token.token_type == TokenType.T_IS_UNIQUE:701 token_type = token.token_type702 token = self.get_token()703 self.compare_tokens(token, TokenType.T_EQUALS)704 token = self.get_token()705 self.compare_tokens(token, TokenType.T_STRING_VALUE)706 if token_type == TokenType.T_IS_ORDERED:707 isOrdered = token.value708 elif token_type == TokenType.T_IS_UNIQUE:709 isUnique = token.value710 token = self.get_token()711 direction = self.parse_parameter_direction(token)712 token = self.get_token()713 if token.token_type != TokenType.T_SLASH:714 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)715 description = self.parse_owned_parameter_description()716 owned_parameter = parser_objects.OwnedParameter(id, name, description[0], isOrdered, isUnique, direction, description[1], description[2], description[3], short_type)717 return owned_parameter718 else:719 token = self.get_token()720 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)721 owned_parameter = parser_objects.OwnedParameter(id, name, None, isOrdered, isUnique, direction, None, None, None, short_type)722 return owned_parameter723 # owned parameter description = ">", [type], [upper limit], [lower limit], [default value], "</ownedParameter>";724 def parse_owned_parameter_description(self):725 type = self.parse_type()726 upper_limit = self.parse_upper_limit()727 lower_limit = self.parse_lower_limit()728 default_value = self.parse_default_value()729 if type is None and default_value[1] is not None:730 type = default_value[1]731 token = self.get_token()732 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)733 token = self.get_token()734 self.compare_tokens(token, TokenType.T_SLASH)735 token = self.get_token()736 self.compare_tokens(token, TokenType.T_OWNED_PARAMETER)737 token = self.get_token()738 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)739 return [type, upper_limit, lower_limit, default_value[0]]740 # parameter direction = " direction=", direction type;741 # direction type = "return" | "out" | "inout";742 def parse_parameter_direction(self, tok):743 if tok.token_type != TokenType.T_DIRECTION:744 self.current_token -= 1745 return '"in"'746 token = self.get_token()747 self.compare_tokens(token, TokenType.T_EQUALS)748 token = self.get_token()749 self.compare_tokens(token, TokenType.T_STRING_VALUE)750 return token.value751 # association = '"uml:Association"', " xmi:id=", string value, " memberEnd=", double string value, ">", owned end;752 def parse_association(self):753 token = self.get_token()754 self.compare_tokens(token, TokenType.T_XMI_ID)755 token = self.get_token()756 self.compare_tokens(token, TokenType.T_EQUALS)757 token = self.get_token()758 self.compare_tokens(token, TokenType.T_STRING_VALUE)759 id = token.value760 token = self.get_token()761 self.compare_tokens(token, TokenType.T_MEMBER_END)762 token = self.get_token()763 self.compare_tokens(token, TokenType.T_EQUALS)764 token = self.get_token()765 self.compare_tokens(token, TokenType.T_DOUBLE_STRING_VALUE)766 member_end = token.value767 token = self.get_token()768 if token.token_type == TokenType.T_SLASH:769 token = self.get_token()770 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)771 association = parser_objects.Association(id, member_end, None)772 return association773 elif token.token_type == TokenType.T_RIGHT_BRACKET:774 owned_end = self.parse_owned_end()775 association = parser_objects.Association(id, member_end, owned_end)776 return association777 else:778 raise SyntaxError(token, "Invalid association ending, expected '/' or '>'")779 # owned end = "<ownedEnd xmi:id=", string value, " name=", string value, visibility, short type, "association=",780 # string value, ">", upper limit, lower limit, "</ownedEnd>";781 def parse_owned_end(self):782 token = self.get_token()783 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)784 token = self.get_token()785 self.compare_tokens(token, TokenType.T_OWNED_END)786 token = self.get_token()787 self.compare_tokens(token, TokenType.T_XMI_ID)788 token = self.get_token()789 self.compare_tokens(token, TokenType.T_EQUALS)790 token = self.get_token()791 self.compare_tokens(token, TokenType.T_STRING_VALUE)792 id = token.value793 token = self.get_token()794 self.compare_tokens(token, TokenType.T_NAME)795 token = self.get_token()796 self.compare_tokens(token, TokenType.T_EQUALS)797 token = self.get_token()798 self.compare_tokens(token, TokenType.T_STRING_VALUE)799 name = token.value800 visibility = self.parse_visibility()801 type = self.parse_short_type()802 token = self.get_token()803 self.compare_tokens(token, TokenType.T_ASSOCIATION)804 token = self.get_token()805 self.compare_tokens(token, TokenType.T_EQUALS)806 token = self.get_token()807 self.compare_tokens(token, TokenType.T_STRING_VALUE)808 association = token.value809 token = self.get_token()810 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)811 upper_limit = self.parse_upper_limit()812 lower_limit = self.parse_lower_limit()813 token = self.get_token()814 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)815 token = self.get_token()816 self.compare_tokens(token, TokenType.T_SLASH)817 token = self.get_token()818 self.compare_tokens(token, TokenType.T_OWNED_END)819 token = self.get_token()820 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)821 self.parse_packaged_element_end()822 owned_end = parser_objects.OwnedEnd(id, name, visibility, type, association, upper_limit, lower_limit)823 return owned_end824 # upper limit = "<upperValue xmi:type=", string value, " xmi:id=", string value, [" value=", ("1" | "*")] ,"/>";825 def parse_upper_limit(self):826 token = self.get_token()827 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)828 token = self.get_token()829 if token.token_type != TokenType.T_UPPER_VALUE:830 self.current_token -= 2831 return None832 self.compare_tokens(token, TokenType.T_UPPER_VALUE)833 token = self.get_token()834 self.compare_tokens(token, TokenType.T_XMI_TYPE)835 token = self.get_token()836 self.compare_tokens(token, TokenType.T_EQUALS)837 token = self.get_token()838 self.compare_tokens(token, TokenType.T_STRING_VALUE)839 type = token.value840 token = self.get_token()841 self.compare_tokens(token, TokenType.T_XMI_ID)842 token = self.get_token()843 self.compare_tokens(token, TokenType.T_EQUALS)844 token = self.get_token()845 self.compare_tokens(token, TokenType.T_STRING_VALUE)846 id = token.value847 token = self.get_token()848 value = None849 if token.token_type == TokenType.T_VALUE:850 token = self.get_token()851 self.compare_tokens(token, TokenType.T_EQUALS)852 token = self.get_token()853 self.compare_tokens(token, TokenType.T_STRING_VALUE)854 value = token.value855 token = self.get_token()856 self.compare_tokens(token, TokenType.T_SLASH)857 token = self.get_token()858 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)859 upper_limit = parser_objects.Limit(type, id, value)860 return upper_limit861 # lower limit = "<lowerValue xmi:type=", string value, " xmi:id=", string value, [" value=", ("1" | "*")] ,"/>";862 def parse_lower_limit(self):863 token = self.get_token()864 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)865 token = self.get_token()866 if token.token_type != TokenType.T_LOWER_VALUE:867 self.current_token -= 2868 return None869 self.compare_tokens(token, TokenType.T_LOWER_VALUE)870 token = self.get_token()871 self.compare_tokens(token, TokenType.T_XMI_TYPE)872 token = self.get_token()873 self.compare_tokens(token, TokenType.T_EQUALS)874 token = self.get_token()875 self.compare_tokens(token, TokenType.T_STRING_VALUE)876 type = token.value877 token = self.get_token()878 self.compare_tokens(token, TokenType.T_XMI_ID)879 token = self.get_token()880 self.compare_tokens(token, TokenType.T_EQUALS)881 token = self.get_token()882 self.compare_tokens(token, TokenType.T_STRING_VALUE)883 id = token.value884 token = self.get_token()885 value = None886 if token.token_type == TokenType.T_VALUE:887 token = self.get_token()888 self.compare_tokens(token, TokenType.T_EQUALS)889 token = self.get_token()890 self.compare_tokens(token, TokenType.T_STRING_VALUE)891 value = token.value892 token = self.get_token()893 self.compare_tokens(token, TokenType.T_SLASH)894 token = self.get_token()895 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)896 lower_limit = parser_objects.Limit(type, id, value)897 return lower_limit898 # short type = " type=", string value;899 def parse_short_type(self):900 token = self.get_token()901 if token.token_type != TokenType.T_TYPE:902 self.current_token -= 1903 return None904 self.compare_tokens(token, TokenType.T_TYPE)905 token = self.get_token()906 self.compare_tokens(token, TokenType.T_EQUALS)907 token = self.get_token()908 self.compare_tokens(token, TokenType.T_STRING_VALUE)909 return token.value910 # "</packagedElement>"911 def parse_packaged_element_end(self):912 msg = "Packaged element ended incorrectly!"913 token = self.get_token()914 self.compare_tokens(token, TokenType.T_LEFT_BRACKET, msg)915 token = self.get_token()916 self.compare_tokens(token, TokenType.T_SLASH, msg)917 token = self.get_token()918 self.compare_tokens(token, TokenType.T_PACKAGED_ELEMENT, msg)919 token = self.get_token()920 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET, msg)921 # profile application = "<profileApplication xmi:id=", id, ">", eannotation,922 # applied profile, "</profileApplication>";923 def parse_profile_application(self):924 token = self.get_token()925 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)926 token = self.get_token()927 if token.token_type != TokenType.T_PROFILE_APPLICATION:928 self.current_token -= 2929 return None930 self.compare_tokens(token, TokenType.T_PROFILE_APPLICATION)931 token = self.get_token()932 self.compare_tokens(token, TokenType.T_XMI_ID)933 token = self.get_token()934 self.compare_tokens(token, TokenType.T_EQUALS)935 token = self.get_token()936 self.compare_tokens(token, TokenType.T_STRING_VALUE)937 id = token.value938 token = self.get_token()939 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)940 eannotation = self.parse_eannotation()941 href = self.parse_applied_profile()942 token = self.get_token()943 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)944 token = self.get_token()945 self.compare_tokens(token, TokenType.T_SLASH)946 token = self.get_token()947 self.compare_tokens(token, TokenType.T_PROFILE_APPLICATION)948 token = self.get_token()949 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)950 profile_application = parser_objects.ProfileApplication(eannotation, id, href)951 return profile_application952 # eannotation = "<eAnnotations xmi:id=", string value, " source=", string value, ">", references, "</eAnnotations>";953 def parse_eannotation(self):954 token = self.get_token()955 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)956 token = self.get_token()957 self.compare_tokens(token, TokenType.T_EANNOTATIONS)958 token = self.get_token()959 self.compare_tokens(token, TokenType.T_XMI_ID)960 token = self.get_token()961 self.compare_tokens(token, TokenType.T_EQUALS)962 token = self.get_token()963 self.compare_tokens(token, TokenType.T_STRING_VALUE)964 id = token.value965 token = self.get_token()966 self.compare_tokens(token, TokenType.T_SOURCE)967 token = self.get_token()968 self.compare_tokens(token, TokenType.T_EQUALS)969 token = self.get_token()970 self.compare_tokens(token, TokenType.T_STRING_VALUE)971 source = token.value972 token = self.get_token()973 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)974 type, href = self.parse_references()975 token = self.get_token()976 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)977 token = self.get_token()978 self.compare_tokens(token, TokenType.T_SLASH)979 token = self.get_token()980 self.compare_tokens(token, TokenType.T_EANNOTATIONS)981 token = self.get_token()982 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)983 eannotation = parser_objects.EAnnotation(id, source, type, href)984 return eannotation985 # references = '<references xmi:type="ecore:EPackage" href=', string value, "/>";986 def parse_references(self):987 token = self.get_token()988 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)989 token = self.get_token()990 self.compare_tokens(token, TokenType.T_REFERENCES)991 token = self.get_token()992 self.compare_tokens(token, TokenType.T_XMI_TYPE)993 token = self.get_token()994 self.compare_tokens(token, TokenType.T_EQUALS)995 token = self.get_token()996 self.compare_tokens(token, TokenType.T_STRING_VALUE)997 type = token.value998 token = self.get_token()999 self.compare_tokens(token, TokenType.T_HREF)1000 token = self.get_token()1001 self.compare_tokens(token, TokenType.T_EQUALS)1002 token = self.get_token()1003 self.compare_tokens(token, TokenType.T_STRING_VALUE)1004 href = token.value1005 token = self.get_token()1006 self.compare_tokens(token, TokenType.T_SLASH)1007 token = self.get_token()1008 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)1009 return type, href1010 # applied profile = "<appliedProfile href=", path, "/>";1011 def parse_applied_profile(self):1012 token = self.get_token()1013 self.compare_tokens(token, TokenType.T_LEFT_BRACKET)1014 token = self.get_token()1015 self.compare_tokens(token, TokenType.T_APPLIED_PROFILE)1016 token = self.get_token()1017 self.compare_tokens(token, TokenType.T_HREF)1018 token = self.get_token()1019 self.compare_tokens(token, TokenType.T_EQUALS)1020 token = self.get_token()1021 self.compare_tokens(token, TokenType.T_STRING_VALUE)1022 href = token.value1023 token = self.get_token()1024 self.compare_tokens(token, TokenType.T_SLASH)1025 token = self.get_token()1026 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET)1027 return href1028 # parse </uml:Model> expression1029 def parse_model_end(self):1030 msg = "Model ended incorrectly!"1031 token = self.get_token()1032 self.compare_tokens(token, TokenType.T_LEFT_BRACKET, msg)1033 token = self.get_token()1034 self.compare_tokens(token, TokenType.T_SLASH, msg)1035 token = self.get_token()1036 self.compare_tokens(token, TokenType.T_UML_MODEL, msg)1037 token = self.get_token()1038 self.compare_tokens(token, TokenType.T_RIGHT_BRACKET, msg)1039 token = self.get_token()...

Full Screen

Full Screen

test_restclient.py

Source:test_restclient.py Github

copy

Full Screen

1# Copyright 2017 IBM Corp.2#3# Licensed under the Apache License, Version 2.0 (the "License"); you may4# not use this file except in compliance with the License. You may obtain5# a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the12# License for the specific language governing permissions and limitations13# under the License.14import json15import mock16import requests17import unittest18from zvmconnector import restclient19from zvmsdk import config20CONF = config.CONF21class FakeResp(object):22 def __init__(self):23 self.content = '{"output": "{}"}'24class RESTClientTestCase(unittest.TestCase):25 """Testcases for RESTClient."""26 def setUp(self):27 self.client = restclient.RESTClient(ssl_enabled=False)28 self.fake_userid = 'userid01'29 self.base_url = 'http://127.0.0.1:8888'30 self.headers = {'Content-Type': 'application/json'}31 self.headers.update(self.headers or {})32 self.response = FakeResp()33 self.client_ssl = restclient.RESTClient(ssl_enabled=True)34 self.base_url_ssl = 'https://127.0.0.1:8888'35 def test_init_ComputeAPI(self):36 self.assertTrue(isinstance(self.client, restclient.RESTClient))37 def _tmp_token(self):38 token = '1234567890'39 return token40 @mock.patch.object(requests, 'request')41 @mock.patch('zvmconnector.restclient.RESTClient._get_token')42 def test_guest_create(self, get_token, request):43 # method = 'POST'44 # url = '/guests'45 disks = [{'size': '3g', 'is_boot_disk': True}]46 # body = {'guest': {'userid': self.fake_userid,47 # 'vcpus': 1,48 # 'memory': 1024,49 # 'disk_list': disks,50 # 'user_profile': 'profile'51 # }}52 # body = json.dumps(body)53 # header = self.headers54 # full_uri = self.base_url + url55 request.return_value = self.response56 get_token.return_value = self._tmp_token()57 self.client.call("guest_create", self.fake_userid,58 1, 1024, disk_list=disks,59 user_profile='profile')60 # request.assert_called_with(method, full_uri,61 # data=body, headers=header,62 # verify=False)63 @mock.patch.object(requests, 'request')64 @mock.patch('zvmconnector.restclient.RESTClient._get_token')65 def test_guest_list(self, get_token, request):66 method = 'GET'67 url = '/guests'68 body = None69 header = self.headers70 full_uri = self.base_url + url71 request.return_value = self.response72 get_token.return_value = self._tmp_token()73 self.client.call("guest_list")74 request.assert_called_with(method, full_uri,75 data=body, headers=header,76 verify=False)77 @mock.patch.object(requests, 'request')78 @mock.patch('zvmconnector.restclient.RESTClient._get_token')79 def test_guest_inspect_stats(self, get_token, request):80 method = 'GET'81 url = '/guests/stats?userid=%s' % self.fake_userid82 body = None83 header = self.headers84 full_uri = self.base_url + url85 request.return_value = self.response86 get_token.return_value = self._tmp_token()87 self.client.call("guest_inspect_stats", self.fake_userid)88 request.assert_called_with(method, full_uri,89 data=body, headers=header,90 verify=False)91 fake_userid_string = 'userid1, userid2, userid3,userid4'92 url = '/guests/stats?userid=%s' % fake_userid_string93 full_uri = self.base_url + url94 self.client.call("guest_inspect_stats", fake_userid_string)95 request.assert_called_with(method, full_uri,96 data=body, headers=header,97 verify=False)98 @mock.patch.object(requests, 'request')99 @mock.patch('zvmconnector.restclient.RESTClient._get_token')100 def test_guest_inspect_vnics(self, get_token, request):101 method = 'GET'102 url = '/guests/interfacestats?userid=%s' % self.fake_userid103 body = None104 header = self.headers105 full_uri = self.base_url + url106 request.return_value = self.response107 get_token.return_value = self._tmp_token()108 self.client.call("guest_inspect_vnics", self.fake_userid)109 request.assert_called_with(method, full_uri,110 data=body, headers=header,111 verify=False)112 fake_userid_string = 'userid1, userid2, userid3,userid4'113 url = '/guests/interfacestats?userid=%s' % fake_userid_string114 full_uri = self.base_url + url115 self.client.call("guest_inspect_vnics", fake_userid_string)116 request.assert_called_with(method, full_uri,117 data=body, headers=header,118 verify=False)119 @mock.patch.object(requests, 'request')120 @mock.patch('zvmconnector.restclient.RESTClient._get_token')121 def test_guests_get_nic_info(self, get_token, request):122 method = 'GET'123 url = '/guests/nics?userid=%s&nic_id=%s&vswitch=%s' % (124 self.fake_userid,125 '1000',126 'xcatvsw1')127 body = None128 header = self.headers129 full_uri = self.base_url + url130 request.return_value = self.response131 get_token.return_value = self._tmp_token()132 self.client.call("guests_get_nic_info", userid=self.fake_userid,133 nic_id='1000', vswitch='xcatvsw1')134 request.assert_called_with(method, full_uri,135 data=body, headers=header,136 verify=False)137 @mock.patch.object(requests, 'request')138 @mock.patch('zvmconnector.restclient.RESTClient._get_token')139 def test_guest_delete(self, get_token, request):140 method = 'DELETE'141 url = '/guests/%s' % self.fake_userid142 body = None143 header = self.headers144 full_uri = self.base_url + url145 request.return_value = self.response146 get_token.return_value = self._tmp_token()147 self.client.call("guest_delete", self.fake_userid)148 request.assert_called_with(method, full_uri,149 data=body, headers=header,150 verify=False)151 @mock.patch.object(requests, 'request')152 @mock.patch('zvmconnector.restclient.RESTClient._get_token')153 def test_guest_get_definition_info(self, get_token, request):154 method = 'GET'155 url = '/guests/%s' % self.fake_userid156 body = None157 header = self.headers158 full_uri = self.base_url + url159 request.return_value = self.response160 get_token.return_value = self._tmp_token()161 self.client.call("guest_get_definition_info", self.fake_userid)162 request.assert_called_with(method, full_uri,163 data=body, headers=header,164 verify=False)165 @mock.patch.object(requests, 'request')166 @mock.patch('zvmconnector.restclient.RESTClient._get_token')167 def test_guest_start(self, get_token, request):168 method = 'POST'169 url = '/guests/%s/action' % self.fake_userid170 body = {'action': 'start'}171 body = json.dumps(body)172 header = self.headers173 full_uri = self.base_url + url174 request.return_value = self.response175 get_token.return_value = self._tmp_token()176 self.client.call("guest_start", self.fake_userid)177 request.assert_called_with(method, full_uri,178 data=body, headers=header,179 verify=False)180 @mock.patch.object(requests, 'request')181 @mock.patch('zvmconnector.restclient.RESTClient._get_token')182 def test_guest_stop(self, get_token, request):183 method = 'POST'184 url = '/guests/%s/action' % self.fake_userid185 body = {'action': 'stop'}186 body = json.dumps(body)187 header = self.headers188 full_uri = self.base_url + url189 request.return_value = self.response190 get_token.return_value = self._tmp_token()191 self.client.call("guest_stop", self.fake_userid)192 request.assert_called_with(method, full_uri,193 data=body, headers=header,194 verify=False)195 @mock.patch.object(requests, 'request')196 @mock.patch('zvmconnector.restclient.RESTClient._get_token')197 def test_guest_softstop(self, get_token, request):198 method = 'POST'199 url = '/guests/%s/action' % self.fake_userid200 body = {'action': 'softstop'}201 body = json.dumps(body)202 header = self.headers203 full_uri = self.base_url + url204 request.return_value = self.response205 get_token.return_value = self._tmp_token()206 self.client.call("guest_softstop", self.fake_userid)207 request.assert_called_with(method, full_uri,208 data=body, headers=header,209 verify=False)210 @mock.patch.object(requests, 'request')211 @mock.patch('zvmconnector.restclient.RESTClient._get_token')212 def test_guest_softstop_parameter_set_zero(self, get_token, request):213 method = 'POST'214 url = '/guests/%s/action' % self.fake_userid215 body = {'action': 'softstop', 'timeout': 0, 'poll_interval': 0}216 body = json.dumps(body)217 header = self.headers218 full_uri = self.base_url + url219 request.return_value = self.response220 get_token.return_value = self._tmp_token()221 self.client.call("guest_softstop", self.fake_userid,222 timeout=0, poll_interval=0)223 request.assert_called_with(method, full_uri,224 data=body, headers=header,225 verify=False)226 @mock.patch.object(requests, 'request')227 @mock.patch('zvmconnector.restclient.RESTClient._get_token')228 def test_guest_pause(self, get_token, request):229 method = 'POST'230 url = '/guests/%s/action' % self.fake_userid231 body = {'action': 'pause'}232 body = json.dumps(body)233 header = self.headers234 full_uri = self.base_url + url235 request.return_value = self.response236 get_token.return_value = self._tmp_token()237 self.client.call("guest_pause", self.fake_userid)238 request.assert_called_with(method, full_uri,239 data=body, headers=header,240 verify=False)241 @mock.patch.object(requests, 'request')242 @mock.patch('zvmconnector.restclient.RESTClient._get_token')243 def test_guest_unpause(self, get_token, request):244 method = 'POST'245 url = '/guests/%s/action' % self.fake_userid246 body = {'action': 'unpause'}247 body = json.dumps(body)248 header = self.headers249 full_uri = self.base_url + url250 request.return_value = self.response251 get_token.return_value = self._tmp_token()252 self.client.call("guest_unpause", self.fake_userid)253 request.assert_called_with(method, full_uri,254 data=body, headers=header,255 verify=False)256 @mock.patch.object(requests, 'request')257 @mock.patch('zvmconnector.restclient.RESTClient._get_token')258 def test_guest_reboot(self, get_token, request):259 method = 'POST'260 url = '/guests/%s/action' % self.fake_userid261 body = {'action': 'reboot'}262 body = json.dumps(body)263 header = self.headers264 full_uri = self.base_url + url265 request.return_value = self.response266 get_token.return_value = self._tmp_token()267 self.client.call("guest_reboot", self.fake_userid)268 request.assert_called_with(method, full_uri,269 data=body, headers=header,270 verify=False)271 @mock.patch.object(requests, 'request')272 @mock.patch('zvmconnector.restclient.RESTClient._get_token')273 def test_guest_reset(self, get_token, request):274 method = 'POST'275 url = '/guests/%s/action' % self.fake_userid276 body = {'action': 'reset'}277 body = json.dumps(body)278 header = self.headers279 full_uri = self.base_url + url280 request.return_value = self.response281 get_token.return_value = self._tmp_token()282 self.client.call("guest_reset", self.fake_userid)283 request.assert_called_with(method, full_uri,284 data=body, headers=header,285 verify=False)286 @mock.patch.object(requests, 'request')287 @mock.patch('zvmconnector.restclient.RESTClient._get_token')288 def test_guest_get_console_output(self, get_token, request):289 method = 'POST'290 url = '/guests/%s/action' % self.fake_userid291 body = {'action': 'get_console_output'}292 body = json.dumps(body)293 header = self.headers294 full_uri = self.base_url + url295 request.return_value = self.response296 get_token.return_value = self._tmp_token()297 self.client.call("guest_get_console_output", self.fake_userid)298 request.assert_called_with(method, full_uri,299 data=body, headers=header,300 verify=False)301 @mock.patch.object(requests, 'request')302 @mock.patch('zvmconnector.restclient.RESTClient._get_token')303 def test_guest_capture(self, get_token, request):304 method = 'POST'305 url = '/guests/%s/action' % self.fake_userid306 body = {'action': 'capture',307 'image': 'image_captured'}308 body = json.dumps(body)309 header = self.headers310 full_uri = self.base_url + url311 request.return_value = self.response312 get_token.return_value = self._tmp_token()313 self.client.call("guest_capture", self.fake_userid,314 'image_captured')315 request.assert_called_with(method, full_uri,316 data=body, headers=header,317 verify=False)318 @mock.patch.object(requests, 'request')319 @mock.patch('zvmconnector.restclient.RESTClient._get_token')320 def test_guest_deploy(self, get_token, request):321 method = 'POST'322 url = '/guests/%s/action' % self.fake_userid323 body = {'action': 'capture',324 'image': 'image_captured'}325 body = json.dumps(body)326 header = self.headers327 full_uri = self.base_url + url328 request.return_value = self.response329 get_token.return_value = self._tmp_token()330 self.client.call("guest_capture", self.fake_userid,331 'image_captured')332 request.assert_called_with(method, full_uri,333 data=body, headers=header,334 verify=False)335 @mock.patch.object(requests, 'request')336 @mock.patch('zvmconnector.restclient.RESTClient._get_token')337 def test_guest_get_info(self, get_token, request):338 method = 'GET'339 url = '/guests/%s/info' % self.fake_userid340 body = None341 header = self.headers342 full_uri = self.base_url + url343 request.return_value = self.response344 get_token.return_value = self._tmp_token()345 self.client.call("guest_get_info", self.fake_userid)346 request.assert_called_with(method, full_uri,347 data=body, headers=header,348 verify=False)349 @mock.patch.object(requests, 'request')350 @mock.patch('zvmconnector.restclient.RESTClient._get_token')351 def test_guest_get_user_direct(self, get_token, request):352 method = 'GET'353 url = '/guests/%s/user_direct' % self.fake_userid354 body = None355 header = self.headers356 full_uri = self.base_url + url357 request.return_value = self.response358 get_token.return_value = self._tmp_token()359 self.client.call("guest_get_user_direct", self.fake_userid)360 request.assert_called_with(method, full_uri,361 data=body, headers=header,362 verify=False)363 @mock.patch.object(requests, 'request')364 @mock.patch('zvmconnector.restclient.RESTClient._get_token')365 def test_guest_get_info_ssl(self, get_token, request):366 method = 'GET'367 url = '/guests/%s/info' % self.fake_userid368 body = None369 header = self.headers370 full_uri = self.base_url_ssl + url371 request.return_value = self.response372 get_token.return_value = self._tmp_token()373 self.client_ssl.call("guest_get_info", self.fake_userid)374 request.assert_called_with(method, full_uri,375 data=body, headers=header,376 verify=False)377 @mock.patch.object(requests, 'request')378 @mock.patch('zvmconnector.restclient.RESTClient._get_token')379 def test_guest_create_nic(self, get_token, request):380 # method = 'POST'381 # url = '/guests/%s/nic' % self.fake_userid382 body = {'nic': {'vdev': '123', 'nic_id': '1234',383 'mac_addr': 'xx:xx:xx:xx:xx:xx',384 'active': False}}385 body = json.dumps(body)386 # header = self.headers387 # full_uri = self.base_url + url388 request.return_value = self.response389 get_token.return_value = self._tmp_token()390 self.client.call("guest_create_nic", self.fake_userid,391 vdev='123', nic_id='1234',392 mac_addr='xx:xx:xx:xx:xx:xx',393 active=False)394 request.assert_called_once()395 # request.assert_called_with(method, full_uri,396 # data=body, headers=header,397 # verify=False)398 @mock.patch.object(requests, 'request')399 @mock.patch('zvmconnector.restclient.RESTClient._get_token')400 def test_guest_delete_nic(self, get_token, request):401 method = 'DELETE'402 url = '/guests/%s/nic/%s' % (self.fake_userid, '123')403 body = {'active': False}404 body = json.dumps(body)405 header = self.headers406 full_uri = self.base_url + url407 request.return_value = self.response408 get_token.return_value = self._tmp_token()409 self.client.call("guest_delete_nic", self.fake_userid, '123',410 active=False)411 request.assert_called_with(method, full_uri,412 data=body, headers=header,413 verify=False)414 @mock.patch.object(requests, 'request')415 @mock.patch('zvmconnector.restclient.RESTClient._get_token')416 def test_guest_nic_couple_to_vswitch(self, get_token, request):417 method = 'PUT'418 url = '/guests/%s/nic/%s' % (self.fake_userid, '123')419 body = {'info': {'couple': True,420 'vswitch': 'vswitch1',421 'active': False}}422 body = json.dumps(body)423 header = self.headers424 full_uri = self.base_url + url425 request.return_value = self.response426 get_token.return_value = self._tmp_token()427 self.client.call("guest_nic_couple_to_vswitch", self.fake_userid,428 '123', 'vswitch1', active=False)429 request.assert_called_with(method, full_uri,430 data=body, headers=header,431 verify=False)432 @mock.patch.object(requests, 'request')433 @mock.patch('zvmconnector.restclient.RESTClient._get_token')434 def test_guest_nic_couple_to_vswitch_vlan_id(self, get_token, request):435 method = 'PUT'436 url = '/guests/%s/nic/%s' % (self.fake_userid, '123')437 body = {'info': {'couple': True,438 'vswitch': 'vswitch1',439 'vlan_id': 1234,440 'active': False}}441 body = json.dumps(body)442 header = self.headers443 full_uri = self.base_url + url444 request.return_value = self.response445 get_token.return_value = self._tmp_token()446 self.client.call("guest_nic_couple_to_vswitch", self.fake_userid,447 '123', 'vswitch1', vlan_id=1234, active=False)448 request.assert_called_with(method, full_uri,449 data=body, headers=header,450 verify=False)451 @mock.patch.object(requests, 'request')452 @mock.patch('zvmconnector.restclient.RESTClient._get_token')453 def test_guest_nic_uncouple_from_vswitch(self, get_token, request):454 method = 'PUT'455 url = '/guests/%s/nic/%s' % (self.fake_userid, '123')456 body = {'info': {'couple': False,457 'active': False}}458 body = json.dumps(body)459 header = self.headers460 full_uri = self.base_url + url461 request.return_value = self.response462 get_token.return_value = self._tmp_token()463 self.client.call("guest_nic_uncouple_from_vswitch", self.fake_userid,464 '123', active=False)465 request.assert_called_with(method, full_uri,466 data=body, headers=header,467 verify=False)468 @mock.patch.object(requests, 'request')469 @mock.patch('zvmconnector.restclient.RESTClient._get_token')470 def test_guest_create_network_interface(self, get_token, request):471 method = 'POST'472 networks = [{'ip_addr': '12.12.12.12'}]473 url = '/guests/%s/interface' % self.fake_userid474 body = {'interface': {'os_version': 'rhel7.2',475 'guest_networks': networks,476 'active': False}}477 body = json.dumps(body)478 header = self.headers479 full_uri = self.base_url + url480 request.return_value = self.response481 get_token.return_value = self._tmp_token()482 self.client.call("guest_create_network_interface", self.fake_userid,483 'rhel7.2', networks, active=False)484 request.assert_called_with(method, full_uri,485 data=body, headers=header,486 verify=False)487 @mock.patch.object(requests, 'request')488 @mock.patch('zvmconnector.restclient.RESTClient._get_token')489 def test_guest_delete_network_interface(self, get_token, request):490 method = 'DELETE'491 url = '/guests/%s/interface' % self.fake_userid492 body = {'interface': {'os_version': 'rhel7.2',493 'vdev': '123',494 'active': False}}495 body = json.dumps(body)496 header = self.headers497 full_uri = self.base_url + url498 request.return_value = self.response499 get_token.return_value = self._tmp_token()500 self.client.call("guest_delete_network_interface", self.fake_userid,501 'rhel7.2', '123', active=False)502 request.assert_called_with(method, full_uri,503 data=body, headers=header,504 verify=False)505 @mock.patch.object(requests, 'request')506 @mock.patch('zvmconnector.restclient.RESTClient._get_token')507 def test_guest_get_power_state(self, get_token, request):508 method = 'GET'509 url = '/guests/%s/power_state' % self.fake_userid510 body = None511 header = self.headers512 full_uri = self.base_url + url513 request.return_value = self.response514 get_token.return_value = self._tmp_token()515 self.client.call("guest_get_power_state", self.fake_userid)516 request.assert_called_with(method, full_uri,517 data=body, headers=header,518 verify=False)519 @mock.patch.object(requests, 'request')520 @mock.patch('zvmconnector.restclient.RESTClient._get_token')521 def test_guest_create_disks(self, get_token, request):522 method = 'POST'523 disks = [{'size': '3g'}]524 url = '/guests/%s/disks' % self.fake_userid525 body = {'disk_info': {'disk_list': disks}}526 body = json.dumps(body)527 header = self.headers528 full_uri = self.base_url + url529 request.return_value = self.response530 get_token.return_value = self._tmp_token()531 self.client.call("guest_create_disks", self.fake_userid, disks)532 request.assert_called_with(method, full_uri,533 data=body, headers=header,534 verify=False)535 @mock.patch.object(requests, 'request')536 @mock.patch('zvmconnector.restclient.RESTClient._get_token')537 def test_guest_delete_disks(self, get_token, request):538 method = 'DELETE'539 vdevs = ['0101', '0102']540 url = '/guests/%s/disks' % self.fake_userid541 body = {'vdev_info': {'vdev_list': vdevs}}542 body = json.dumps(body)543 header = self.headers544 full_uri = self.base_url + url545 request.return_value = self.response546 get_token.return_value = self._tmp_token()547 self.client.call("guest_delete_disks", self.fake_userid, vdevs)548 request.assert_called_with(method, full_uri,549 data=body, headers=header,550 verify=False)551 @mock.patch.object(requests, 'request')552 @mock.patch('zvmconnector.restclient.RESTClient._get_token')553 def test_guest_config_minidisks(self, get_token, request):554 method = 'PUT'555 disks = [{'vdev': '0101', 'mntdir': '/mnt/0101'}]556 url = '/guests/%s/disks' % self.fake_userid557 body = {'disk_info': {'disk_list': disks}}558 body = json.dumps(body)559 header = self.headers560 full_uri = self.base_url + url561 request.return_value = self.response562 get_token.return_value = self._tmp_token()563 self.client.call("guest_config_minidisks", self.fake_userid, disks)564 request.assert_called_with(method, full_uri,565 data=body, headers=header,566 verify=False)567 @mock.patch.object(requests, 'request')568 @mock.patch('zvmconnector.restclient.RESTClient._get_token')569 def test_host_get_guest_list(self, get_token, request):570 method = 'GET'571 url = '/host/guests'572 body = None573 header = self.headers574 full_uri = self.base_url + url575 request.return_value = self.response576 get_token.return_value = self._tmp_token()577 self.client.call("host_get_guest_list")578 request.assert_called_with(method, full_uri,579 data=body, headers=header,580 verify=False)581 @mock.patch.object(requests, 'request')582 @mock.patch('zvmconnector.restclient.RESTClient._get_token')583 def test_guest_get_power_state_real(self, get_token, request):584 method = 'GET'585 url = '/guests/%s/power_state_real' % self.fake_userid586 body = None587 header = self.headers588 full_uri = self.base_url + url589 request.return_value = self.response590 get_token.return_value = self._tmp_token()591 self.client.call("guest_get_power_state_real", self.fake_userid)592 request.assert_called_with(method, full_uri,593 data=body, headers=header,594 verify=False)595 @mock.patch.object(requests, 'request')596 @mock.patch('zvmconnector.restclient.RESTClient._get_token')597 def test_host_get_info(self, get_token, request):598 method = 'GET'599 url = '/host'600 body = None601 header = self.headers602 full_uri = self.base_url + url603 request.return_value = self.response604 get_token.return_value = self._tmp_token()605 self.client.call("host_get_info")606 request.assert_called_with(method, full_uri,607 data=body, headers=header,608 verify=False)609 @mock.patch.object(requests, 'request')610 @mock.patch('zvmconnector.restclient.RESTClient._get_token')611 def test_host_diskpool_get_info(self, get_token, request):612 # wait host_diskpool_get_info bug fixed613 pass614 @mock.patch.object(requests, 'request')615 @mock.patch('zvmconnector.restclient.RESTClient._get_token')616 def test_image_import(self, get_token, request):617 method = 'POST'618 image_uri = 'file:///tmp/100.img'619 image_meta = {'os_version': 'rhel7.2', 'md5sum': 'dummy'}620 url = '/images'621 body = {'image': {'image_name': '100.img',622 'url': image_uri,623 'image_meta': image_meta}}624 body = json.dumps(body)625 header = self.headers626 full_uri = self.base_url + url627 request.return_value = self.response628 get_token.return_value = self._tmp_token()629 self.client.call("image_import", '100.img',630 image_uri, image_meta)631 request.assert_called_with(method, full_uri,632 data=body, headers=header,633 verify=False)634 @mock.patch.object(requests, 'request')635 @mock.patch('zvmconnector.restclient.RESTClient._get_token')636 def test_image_delete(self, get_token, request):637 method = 'DELETE'638 url = '/images/%s' % '100.img'639 body = None640 header = self.headers641 full_uri = self.base_url + url642 request.return_value = self.response643 get_token.return_value = self._tmp_token()644 self.client.call("image_delete", '100.img')645 request.assert_called_with(method, full_uri,646 data=body, headers=header,647 verify=False)648 @mock.patch.object(requests, 'request')649 @mock.patch('zvmconnector.restclient.RESTClient._get_token')650 def test_image_export(self, get_token, request):651 method = 'PUT'652 destination = 'file:///tmp/export.img'653 url = '/images/%s' % '100.img'654 body = {'location': {'dest_url': destination}}655 body = json.dumps(body)656 header = self.headers657 full_uri = self.base_url + url658 request.return_value = self.response659 get_token.return_value = self._tmp_token()660 self.client.call("image_export", '100.img',661 destination)662 request.assert_called_with(method, full_uri,663 data=body, headers=header,664 verify=False)665 @mock.patch.object(requests, 'request')666 @mock.patch('zvmconnector.restclient.RESTClient._get_token')667 def test_image_get_root_disk_size(self, get_token, request):668 method = 'GET'669 url = '/images/%s/root_disk_size' % '100.img'670 body = None671 header = self.headers672 full_uri = self.base_url + url673 request.return_value = self.response674 get_token.return_value = self._tmp_token()675 self.client.call("image_get_root_disk_size", '100.img')676 request.assert_called_with(method, full_uri,677 data=body, headers=header,678 verify=False)679 @mock.patch.object(requests, 'request')680 @mock.patch('zvmconnector.restclient.RESTClient._get_token')681 def test_token_create(self, get_token, request):682 method = 'POST'683 url = '/token'684 body = None685 header = self.headers686 full_uri = self.base_url + url687 request.return_value = self.response688 get_token.return_value = self._tmp_token()689 self.client.call("token_create")690 request.assert_called_with(method, full_uri,691 data=body, headers=header,692 verify=False)693 @mock.patch.object(requests, 'request')694 @mock.patch('zvmconnector.restclient.RESTClient._get_token')695 def test_vswitch_get_list(self, get_token, request):696 method = 'GET'697 url = '/vswitches'698 body = None699 header = self.headers700 full_uri = self.base_url + url701 request.return_value = self.response702 get_token.return_value = self._tmp_token()703 self.client.call("vswitch_get_list")704 request.assert_called_with(method, full_uri,705 data=body, headers=header,706 verify=False)707 @mock.patch.object(requests, 'request')708 @mock.patch('zvmconnector.restclient.RESTClient._get_token')709 def test_vswitch_create(self, get_token, request):710 method = 'POST'711 url = '/vswitches'712 body = {'vswitch': {'name': 'dummy'}}713 body = json.dumps(body)714 header = self.headers715 full_uri = self.base_url + url716 request.return_value = self.response717 get_token.return_value = self._tmp_token()718 self.client.call("vswitch_create", 'dummy')719 request.assert_called_with(method, full_uri,720 data=body, headers=header,721 verify=False)722 @mock.patch.object(requests, 'request')723 @mock.patch('zvmconnector.restclient.RESTClient._get_token')724 def test_vswitch_delete(self, get_token, request):725 method = 'DELETE'726 url = '/vswitches/%s' % 'dummy'727 body = None728 header = self.headers729 full_uri = self.base_url + url730 request.return_value = self.response731 get_token.return_value = self._tmp_token()732 self.client.call("vswitch_delete", 'dummy')733 request.assert_called_with(method, full_uri,734 data=body, headers=header,735 verify=False)736 @mock.patch.object(requests, 'request')737 @mock.patch('zvmconnector.restclient.RESTClient._get_token')738 def test_vswitch_grant_user(self, get_token, request):739 method = 'PUT'740 url = '/vswitches/%s' % 'dummy'741 body = {'vswitch': {'grant_userid': self.fake_userid}}742 body = json.dumps(body)743 header = self.headers744 full_uri = self.base_url + url745 request.return_value = self.response746 get_token.return_value = self._tmp_token()747 self.client.call("vswitch_grant_user", 'dummy', self.fake_userid)748 request.assert_called_with(method, full_uri,749 data=body, headers=header,750 verify=False)751 @mock.patch.object(requests, 'request')752 @mock.patch('zvmconnector.restclient.RESTClient._get_token')753 def test_vswitch_revoke_user(self, get_token, request):754 method = 'PUT'755 url = '/vswitches/%s' % 'dummy'756 body = {'vswitch': {'revoke_userid': self.fake_userid}}757 body = json.dumps(body)758 header = self.headers759 full_uri = self.base_url + url760 request.return_value = self.response761 get_token.return_value = self._tmp_token()762 self.client.call("vswitch_revoke_user", 'dummy', self.fake_userid)763 request.assert_called_with(method, full_uri,764 data=body, headers=header,765 verify=False)766 @mock.patch.object(requests, 'request')767 @mock.patch('zvmconnector.restclient.RESTClient._get_token')768 def test_vswitch_set_vlan_id_for_user(self, get_token, request):769 method = 'PUT'770 url = '/vswitches/%s' % 'dummy'771 body = {'vswitch': {'user_vlan_id': {'userid': self.fake_userid,772 'vlanid': 'vlan_id'}}}773 body = json.dumps(body)774 header = self.headers775 full_uri = self.base_url + url776 request.return_value = self.response777 get_token.return_value = self._tmp_token()778 self.client.call("vswitch_set_vlan_id_for_user",779 'dummy', self.fake_userid, 'vlan_id')780 request.assert_called_with(method, full_uri,781 data=body, headers=header,782 verify=False)783 @mock.patch.object(requests, 'request')784 @mock.patch('zvmconnector.restclient.RESTClient._get_token')785 def test_guest_resize_mem(self, get_token, request):786 method = 'POST'787 url = '/guests/%s/action' % self.fake_userid788 body = {'action': 'resize_mem',789 'size': '4g'}790 body = json.dumps(body)791 header = self.headers792 full_uri = self.base_url + url793 request.return_value = self.response794 get_token.return_value = self._tmp_token()795 self.client.call("guest_resize_mem", self.fake_userid,796 '4g')797 request.assert_called_with(method, full_uri,798 data=body, headers=header,799 verify=False)800 @mock.patch.object(requests, 'request')801 @mock.patch('zvmconnector.restclient.RESTClient._get_token')802 def test_guest_live_resize_mem(self, get_token, request):803 method = 'POST'804 url = '/guests/%s/action' % self.fake_userid805 body = {'action': 'live_resize_mem',806 'size': '4g'}807 body = json.dumps(body)808 header = self.headers809 full_uri = self.base_url + url810 request.return_value = self.response811 get_token.return_value = self._tmp_token()812 self.client.call("guest_live_resize_mem", self.fake_userid,813 '4g')814 request.assert_called_with(method, full_uri,815 data=body, headers=header,816 verify=False)817 @mock.patch.object(requests, 'request')818 @mock.patch('zvmconnector.restclient.RESTClient._get_token')819 def test_guest_grow_root_volume(self, get_token, request):820 method = 'POST'821 url = '/guests/%s/action' % self.fake_userid822 body = {'action': 'grow_root_volume',823 'os_version': 'RHEL7.8'}824 body = json.dumps(body)825 header = self.headers826 full_uri = self.base_url + url827 request.return_value = self.response828 get_token.return_value = self._tmp_token()829 self.client.call("guest_grow_root_volume", self.fake_userid,830 'RHEL7.8')831 request.assert_called_with(method, full_uri,832 data=body, headers=header,...

Full Screen

Full Screen

pascal.py

Source:pascal.py Github

copy

Full Screen

...185 print('currentPro:')186 i = self.currentPro187 print('pname=%s, ptype=%s, plev=%d, varNum=%d, fadr=%d, ladr=%d, parameter=%d, parameterIsDefined=%s' % (i.pname, i.ptype, i.plev, i.varNum, i.fadr, i.ladr, i.parameter, i.parameterIsDefined))188 print('----')189 def get_token(self, index=-1, code=False, change=True):190 if index == -1:191 index = self.token_index192 d = ''.join(self.tokens[index].strip('\n')[0:16].split())193 c = int(''.join(self.tokens[index].strip('\n')[17:19].split()))194 if d == 'EOLN':195 logger.info('get EOLN')196 if change:197 self.line += 1198 logger.info('now line is %d, ->%s %d' % (self.line, d, c))199 self.set_token_offset(1)200 return self.get_token(index+1)201 # logger.debug('-> %s' % d)202 if code:203 return c204 else:205 return d206 def set_token_offset(self, offset=0, absolute=0):207 self.char_index = 0208 if offset != 0:209 logger.debug('GrammarAnalysis.set_token_offset(1): get next %d' % offset)210 self.token_index += offset211 elif absolute != 0:212 logger.debug('GrammarAnalysis.set_token_offset(1): turn to %d' % absolute)213 self.token_index = absolute214 else:215 pass216 logger.info('now token offset is %d' % self.token_index)217 def error(self, text):218 logger.error(text)219 open(self.errorfile, 'a').write(text + '\n')220 self.error_cnt += 1221 def do(self):222 self.init()223 logger.debug('GrammarAnalysis.do(1)')224 self.A()225 self.check()226 self.writeVar()227 self.writePro()228 def writeVar(self):229 line = '%16s %16s %1d %s %d %d\n'230 for i in self.var:231 if i.vtype == int:232 types = 'integer'233 else:234 types = ''235 open(self.varfile, 'a').write(line % (i.vname, i.vproc, i.vkind, types, i.vlev, i.vadr))236 def writePro(self):237 line = '%16s %s %d %d %d\n'238 for i in self.pro:239 if i.ptype == int:240 types = 'integer'241 else:242 types = ''243 open(self.profile, 'a').write(line % (i.pname, types, i.plev, i.fadr, i.ladr))244 def A(self):245 logger.debug('GrammarAnalysis.A(1)')246 self.B()247 def B(self):248 logger.debug('GrammarAnalysis.B(1)')249 if self.get_token() == 'begin':250 logger.debug('GrammarAnalysis.B(2): get <begin>')251 self.set_token_offset(offset=1)252 else:253 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'begin'))254 if self.get_token() != 'integer':255 self.set_token_offset(1)256 self.C()257 if self.get_token() == ';':258 logger.debug('GrammarAnalysis.B(3): get <;>')259 self.set_token_offset(1)260 else:261 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ';'))262 if self.get_token() != 'integer' and self.get_token() != 'read' and self.get_token() != 'write' and self.get_token(code=True) != 10:263 self.set_token_offset(1)264 self.M()265 if self.get_token() == 'end':266 logger.debug('GrammarAnalysis.B(4): get <end>')267 self.set_token_offset(1)268 else:269 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'end'))270 def C(self):271 logger.debug('GrammarAnalysis.C(1)')272 self.D()273 self.C_()274 def C_(self):275 logger.debug('GrammarAnalysis.C_(1)')276 self.get_token()277 if self.get_token() == ';' and self.get_token(self.token_index + 1, change=False) == 'integer':278 logger.info('GrammarAnalysis.C(1): get ";" and next is "integer"')279 self.set_token_offset(1)280 self.D()281 self.C_()282 else:283 if self.get_token() == 'integer':284 logger.info('GrammarAnalysis.C(1): get "integer"')285 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ';'))286 self.D()287 self.C_()288 def D(self):289 logger.debug('GrammarAnalysis.D(1)')290 self.get_token()291 if self.get_token(self.token_index + 1, change=False) == 'function':292 logger.info('GrammarAnalysis.D(2): next is "function"')293 self.J()294 else:295 logger.info('GrammarAnalysis.D(3): next is %s NOT "function"' % self.get_token())296 self.E()297 def is_var_exists(self, vname, vproc, vkind):298 for i in self.var:299 logger.info('GrammarAnalysis.is_var_exists(1): check this <%s, %s, %s> == <%s, %s, %s>' % (vname, vproc, vkind, i.vname, i.vproc, i.vkind))300 if i.vname == vname and i.vproc == vproc and i.vkind == vkind:301 return True302 for i in self.pro:303 logger.info('GrammarAnalysis.is_var_exists(1): check this <%s> == <%s>' % (vname, i.pname))304 if i.pname == vname:305 return True306 if vproc != '':307 return self.is_var_exists(vname, '', vkind)308 else:309 return False310 def is_pro_exists(self, vname):311 for i in self.var:312 if vname == i.vname:313 return True314 for i in self.pro:315 if vname == i.pname:316 return True317 return False318 def E(self):319 logger.debug('GrammarAnalysis.E(1)')320 currentVar = Var()321 if self.get_token() == 'integer':322 logger.info('GrammarAnalysis.E(2): get "%s"' % self.get_token())323 self.set_token_offset(1)324 else:325 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'integer'))326 self.set_token_offset(1)327 currentVar.vname = self.get_token()328 currentVar.vproc = self.currentPro.pname329 # if self.token_index == self.currentPro.parameter:330 if currentVar.vproc != '':331 currentVar.vkind = 1332 self.currentPro.parameterIsDefined = 1333 else:334 currentVar.vkind = 0335 currentVar.vtype = int336 currentVar.vlev = self.currentPro.plev337 currentVar.vadr = len(self.var)338 if self.is_var_exists(self.get_token(), self.currentPro.pname, currentVar.vkind):339 self.error('***LINE:%02d Redifine var "%s"' % (self.line, self.get_token()))340 else:341 if self.currentPro.varNum == 0:342 self.currentPro.fadr = currentVar.vadr343 self.currentPro.ladr = currentVar.vadr344 self.currentPro.varNum += 1345 self.var.append(currentVar)346 self.F();347 def F(self):348 logger.debug('GrammarAnalysis.F(1)')349 self.G()350 def G(self):351 logger.debug('GrammarAnalysis.G(1)')352 if self.get_token(code=True) == 10:353 logger.info('GrammarAnalysis.G(2): get const "%s"' % self.get_token())354 self.set_token_offset(1)355 def J(self):356 logger.debug('GrammarAnalysis.J(1)')357 pro_bak = self.currentPro358 if self.get_token() == 'integer':359 self.set_token_offset(1)360 else:361 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'integer'))362 if self.get_token() != 'function':363 self.set_token_offset(1)364 if self.get_token() == 'function':365 self.set_token_offset(1)366 else:367 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'function'))368 if self.get_token(code=True) != 10:369 self.set_token_offset(1)370 self.currentPro.pname = self.get_token()371 self.currentPro.ptype = int372 self.currentPro.plev += 1373 self.currentPro.varNum = 0374 self.currentPro.parameterIsDefined = False375 if self.is_pro_exists(self.get_token()):376 self.error('***LINE:%02d Redefine "%s"' % (self.line, self.get_token()))377 self.G()378 if self.get_token() == '(':379 self.set_token_offset(1)380 else:381 self.error('***LINE:%02d No Symbol "%s"' % (self.line, '('))382 if self.get_token(code=True) != 10:383 self.set_token_offset(1)384 self.currentPro.parameter = self.token_index385 self.K()386 if self.get_token() == ')':387 self.set_token_offset(1)388 else:389 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ')'))390 if self.get_token() != ';':391 self.set_token_offset(1)392 if self.get_token() == ';':393 self.set_token_offset(1)394 else:395 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ';'))396 if self.get_token() != 'begin':397 self.set_token_offset(1)398 self.L()399 self.currentPro = pro_bak400 def K(self):401 logger.debug('GrammarAnalysis.K(1)')402 self.F()403 def L(self):404 logger.debug('GrammarAnalysis.L(1)')405 if self.get_token() == 'begin':406 self.set_token_offset(1)407 else:408 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'begin'))409 if self.get_token() != 'integer':410 self.set_token_offset(1)411 self.C()412 if not self.currentPro.parameterIsDefined:413 self.error('***LINE:%02d No Para "%s"' % (self.line, self.get_token()))414 _ = self.currentPro415 self.pro.append(_)416 if self.get_token() == ';':417 self.set_token_offset(1)418 else:419 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ';'))420 if self.get_token() != 'integer' and self.get_token() != 'read' and self.get_token() != 'write' and self.get_token(code=True) != 10:421 self.set_token_offset(1)422 self.M()423 if self.get_token() == 'end':424 self.set_token_offset(1)425 else:426 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'end'))427 if self.get_token() != ';' and self.get_token() != 'end':428 self.set_token_offset(1)429 def M(self):430 logger.debug('GrammarAnalysis.M(1)')431 self.N()432 self.M_()433 def M_(self):434 logger.debug('GrammarAnalysis.M_(1)')435 if self.get_token() == ';':436 logger.info('GrammarAnalysis.M_(2): get "%s"' % self.get_token())437 self.set_token_offset(1)438 self.N()439 self.M_()440 else:441 if self.get_token() != 'end' and self.get_token() != 'EOF':442 logger.info('GrammarAnalysis.M_(3): get "%s"' % self.get_token())443 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ';'))444 self.N()445 self.M_()446 def N(self):447 logger.debug('GrammarAnalysis.N(1)')448 logger.info('GrammarAnalysis.N(2): get "%s"' % self.get_token())449 if self.get_token() == 'read':450 self.O()451 elif self.get_token() == 'write':452 self.P()453 elif self.get_token() == 'if':454 self.W()455 elif self.get_token(code=True) == 10:456 logger.info('GrammarAnalysis.N(2): get const "%s"' % self.get_token())457 self.Q()458 else:459 self.error('***LINE:%02d Symbol exec error "%s"' % (self.line, self.get_token()))460 self.set_token_offset(1)461 def O(self):462 logger.debug('GrammarAnalysis.O(1)')463 if self.get_token() == 'read':464 self.set_token_offset(1)465 else:466 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ';'))467 if self.get_token() != '(':468 self.set_token_offset(1)469 if self.get_token() == '(':470 self.set_token_offset(1)471 else:472 self.error('***LINE:%02d No Symbol "%s"' % (self.line, '('))473 if self.get_token(code=True) != 10:474 self.set_token_offset(1)475 if not self.is_var_exists(self.get_token(), self.currentPro.pname, False) and not self.is_var_exists(self.get_token(), self.currentPro.pname, True):476 self.error('***LINE:%02d Undefined Symbol "%s"' % (self.line, self.get_token()))477 self.F()478 if self.get_token() == ')':479 self.set_token_offset(1)480 else:481 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ')'))482 if self.get_token() != ';' and self.get_token() != 'end':483 self.set_token_offset()484 def P(self):485 logger.debug('GrammarAnalysis.P(1)')486 if self.get_token() == 'write':487 self.set_token_offset(1)488 else:489 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'write'))490 if self.get_token() != '(':491 self.set_token_offset(1)492 if self.get_token() == '(':493 self.set_token_offset(1)494 else:495 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ')'))496 if self.get_token(code=True) != 10:497 self.set_token_offset(1)498 if not self.is_var_exists(self.get_token(), self.currentPro.pname, False) and not self.is_var_exists(self.get_token(), self.currentPro.pname, True):499 self.error('***LINE:%02d Undefined Symbol "%s"' % (self.line, self.get_token()))500 self.F()501 if self.get_token() == ')':502 self.set_token_offset(1)503 else:504 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ')'))505 if self.get_token() != ';' and self.get_token() != 'end':506 self.set_token_offset(1)507 def Q(self):508 logger.debug('GrammarAnalysis.Q(1)')509 if not self.is_var_exists(self.get_token(), self.currentPro.pname, False) and not self.is_var_exists(self.get_token(), self.currentPro.pname, True):510 logger.info('GrammarAnalysis.Q(2): get "%s"' % self.get_token())511 self.error('***LINE:%02d Undefined Symbol "%s"' % (self.line, self.get_token()))512 self.F()513 if self.get_token() == ':=':514 self.set_token_offset(1)515 else:516 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ':='))517 if self.get_token(code=True) != 10 and self.get_token(code=True) != 11:518 self.set_token_offset(1)519 self.R()520 def R(self):521 logger.debug('GrammarAnalysis.R(1)')522 self.S()523 self.R_()524 def R_(self):525 logger.debug('GrammarAnalysis.R_(1)')526 if self.get_token() == '-':527 logger.info('GrammarAnalysis.R_(2): get "%s"' % self.get_token())528 self.set_token_offset(1)529 self.S()530 self.R_()531 else:532 if self.get_token(code=True) == 10 or self.get_token(code=True) == 11:533 logger.info('GrammarAnalysis.R_(3): get const "%s"' % self.get_token())534 self.S()535 self.R_()536 def S(self):537 logger.debug('GrammarAnalysis.S(1)')538 self.T()539 self.S_()540 def S_(self):541 logger.debug('GrammarAnalysis.S_(1)')542 if self.get_token() == '*':543 logger.info('GrammarAnalysis.S_(2): get const "*"')544 self.set_token_offset(1)545 self.T()546 self.S_()547 else:548 if self.get_token(code=True) == 10 or self.get_token(code=True) == 11:549 logger.info('GrammarAnalysis.S_(3): get const "%s"' % self.get_token())550 self.T()551 self.S_()552 def T(self):553 logger.debug('GrammarAnalysis.T(1)')554 if ord('0') <= ord(self.get_token()[self.char_index]) <= ord('9'):555 logger.info('GrammarAnalysis.T(2): get const "%s"' % self.get_token())556 self.U()557 elif self.get_token(self.token_index + 1, change=False) == '(':558 logger.info('GrammarAnalysis.T(3): get "("')559 self.Z()560 else:561 if not self.is_var_exists(self.get_token(), self.currentPro.pname, False) and not self.is_var_exists(self.get_token(), self.currentPro.pname, True):562 self.error('***LINE:%02d Undefined Symbol "%s"' % (self.line, self.get_token()))563 self.F()564 def U(self):565 logger.debug('GrammarAnalysis.U(1)')566 if self.get_token(code=True) == 11:567 self.set_token_offset(1)568 def W(self):569 logger.debug('GrammarAnalysis.W(1)')570 if self.get_token() == 'if':571 self.set_token_offset(1)572 else:573 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'if'))574 if self.get_token(code=True) != 10 and self.get_token(code=True) != 11:575 self.set_token_offset(1)576 self.X()577 if self.get_token() == 'then':578 self.set_token_offset(1)579 else:580 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'then'))581 if self.get_token() != 'integer' and self.get_token() != 'read' and self.get_token() != 'write' and self.get_token(code=True) != 10:582 self.set_token_offset(1)583 self.N()584 if self.get_token() == 'else':585 self.set_token_offset(1)586 else:587 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'else'))588 if self.get_token() != 'integer' and self.get_token() != 'read' and self.get_token() != 'write' and self.get_token(code=True) != 10:589 self.set_token_offset(1)590 self.N()591 def X(self):592 logger.debug('GrammarAnalysis.X(1)')593 self.R()594 self.Y()595 self.R()596 def Y(self):597 logger.debug('GrammarAnalysis.Y(1)')598 if self.get_token() == '<' or self.get_token() == '<=' or self.get_token() == '>' or self.get_token() == '>=' or self.get_token() == '=' or self.get_token() == '<>':599 self.set_token_offset(1)600 else:601 self.error('***LINE:%02d No Symbol "%s"' % (self.line, 'compair symbol'))602 if self.get_token(code=True) != 10 and self.get_token(code=True) != 11:603 self.set_token_offset(1)604 def Z(self):605 logger.debug('GrammarAnalysis.Z(1)')606 if not self.is_pro_exists(self.get_token()):607 self.error('***LINE:%02d Undefined Symbol "%s"' % (self.line, self.get_token()))608 self.G()609 if self.get_token() == '(':610 logger.info('GrammarAnalysis.Z(2): get "("')611 self.set_token_offset(1)612 else:613 self.error('***LINE:%02d No Symbol "%s"' % (self.line, '('))614 if self.get_token(code=True) != 10 and self.get_token(code) != 11:615 logger.info('GrammarAnalysis.Z(3): get "%s"' % self.get_token())616 self.set_token_offset(1)617 self.R()618 if self.get_token() == ')':619 logger.info('GrammarAnalysis.Z(4): get "%s"' % self.get_token())620 self.currentPro = Pro()621 self.set_token_offset(1)622 else:623 logger.info('GrammarAnalysis.Z(5): get "%s"' % self.get_token())624 self.error('***LINE:%02d No Symbol "%s"' % (self.line, ')'))625 if self.get_token() != '-' and self.get_token() != '*' and self.get_token() != ';' and self.get_token() != 'end':626 self.set_token_offset(1)627class ReadFile:628 def __init__(self, input_file):629 self.input_file = input_file630 try:631 source_lines = open(input_file, 'r').readlines()632 except FileNotFoundError as e:633 logger.error('FileNotFound: %s' % input_file)634 exit(0)635 self.source_code = ''.join(source_lines)636 def get_source_code(self):637 return self.source_code638if __name__ == '__main__':639 # a = LexicalAnalysis('test')...

Full Screen

Full Screen

cparse.py

Source:cparse.py Github

copy

Full Screen

...78 Node.__init__(self,*items)79 def parse(self,lexer,symbols):80 symbols = Symbols(symbols)81 args = ''82 #lexer.get_token()83 if lexer.tok != ')':84 if not lexer.tok:85 self.parse_error(lexer)86 #lexer.unget_token() # unget start of decl87 while lexer.tok != ')':88 node = ParameterDeclaration()89 node.parse(lexer,symbols)90 self.append( node )91 if lexer.tok != ')' and lexer.tok != ',':92 self.parse_error(lexer)93 if lexer.tok == ',':94 lexer.get_token()95 lexer.get_token()96class Pointer(Node):97 """98 """99 def __init__(self,*items):100 Node.__init__(self,*items)101class Array(Node,Parser):102 """103 """104 def __init__(self,*items):105 Node.__init__(self,*items)106 def parse(self,lexer,symbols):107 lexer.get_token() # a number or ']'108 # XX109 # HACK HACK: constant c expressions can appear in here:110 # eg. [ 15 * sizeof (int) - 2 * sizeof (void *) ]111 # XX112 toks = []113 while lexer.tok != ']':114 #self.append( lexer.kind )115 toks.append( lexer.tok )116 lexer.get_token()117 child = " ".join(toks)118 if child == "":119 child = None120 self.append( child )121 lexer.get_token() # read past the ']'122class Tag(Node):123 """124 """125 pass126class Compound(Node,Parser):127 "Struct or Union"128 def __init__(self,*items,**kw):129 Node.__init__(self,*items,**kw)130 def parse(self,lexer,symbols):131 symbols = Symbols(symbols)132 tag = "" # anonymous133 if lexer.tok != '{':134 tag = lexer.tok135 if not ( tag[0]=='_' or tag[0].isalpha() ):136 self.parse_error(lexer ,"expected tag, got '%s'"%tag )137 lexer.get_token()138 if tag:139 self.append(Tag(tag))140 else:141 self.append(Tag())142 self.tag = tag143 if lexer.tok == '{':144 fieldlist = []145 lexer.get_token()146 if lexer.tok != '}':147 if not lexer.tok: self.parse_error(lexer)148 while lexer.tok != '}':149 node = StructDeclaration()150 node.parse(lexer,symbols)151 fieldlist.append( node )152 self += fieldlist153 lexer.get_token()154 if self.verbose: 155 print "%s.__init__() #<--"%(self)156class Struct(Compound):157 """158 """159 pass160class Union(Compound):161 """162 """163 pass164class Enum(Node,Parser):165 """166 """167 def __init__(self,*items,**kw):168 Node.__init__(self,*items,**kw)169 def parse(self,lexer,symbols):170 tag = "" # anonymous171 if lexer.tok != '{':172 tag = lexer.tok173 if not ( tag[0]=='_' or tag[0].isalpha() ):174 self.parse_error(lexer ,"expected tag, got '%s'"%tag )175 lexer.get_token()176 if tag:177 self.append(Tag(tag))178 else:179 self.append(Tag())180 self.tag = tag181 if lexer.tok == '{':182 lexer.get_token()183 if lexer.tok != '}': # XX dopey control flow184 if not lexer.tok: # XX dopey control flow185 self.parse_error(lexer) # XX dopey control flow186 while lexer.tok != '}': # XX dopey control flow187 if lexer.kind is not None:188 self.expected_error(lexer ,"identifier" )189 ident = Identifier(lexer.tok)190 if symbols[ident[0]] is not None:191 self.parse_error(lexer,"%s already defined."%ident[0])192 symbols[ident[0]]=ident193 self.append( ident )194 lexer.get_token()195 if lexer.tok == '=':196 lexer.get_token()197 # ConstantExpr198 # XX hack hack XX199 while lexer.tok!=',' and lexer.tok!='}':200 lexer.get_token()201# if type( lexer.kind ) is not int:202# #self.parse_error(lexer ,"expected integer" )203# # XX hack hack XX204# while lexer.tok!=',' and lexer.tok!='}':205# lexer.get_token()206# else:207# # put initializer into the Identifier208# ident.append( lexer.kind )209# lexer.get_token()210 if lexer.tok != '}':211 if lexer.tok != ',':212 self.expected_error(lexer,"}",",")213 lexer.get_token() # ','214 lexer.get_token()215 if self.verbose:216 print "%s.__init__() #<--"%(self)217class Declarator(Node,Parser):218 """219 """220 def __init__(self,*items):221 Node.__init__(self,*items)222 self.ident = None223 def parse(self,lexer,symbols):224 #Parser.parse_enter(self,lexer)225 stack = []226 # read up to identifier, pushing tokens onto stack227 self.ident = self.parse_identifier(lexer,symbols,stack)228 self.name = ''229 if self.ident is not None:230 self.append( self.ident )231 self.name = self.ident.name232 # now read outwards from identifier233 self.parse_declarator(lexer,symbols,stack)234 #Parser.parse_leave(self,lexer)235 def parse_identifier(self,lexer,symbols,stack):236 if self.verbose:237 print "%s.parse_identifier()"%self238 ident = None239 if lexer.tok != ';':240 while lexer.tok and lexer.kind is not None:241 stack.append( (lexer.tok, lexer.kind) )242 lexer.get_token()243 if lexer.tok:244 ident = Identifier( lexer.tok )245 #stack.append( (ident.name, ident) )246 lexer.get_token()247 if self.verbose:248 print "%s.parse_identifier()=%s"%(self,repr(ident))249 return ident250 def parse_declarator(self,lexer,symbols,stack,level=0):251 if self.verbose:252 print " "*level+"%s.parse_declarator(%s) # --->"%\253 (self,stack)254 if lexer.tok == '[':255 while lexer.tok == '[':256 node = Array()257 node.parse(lexer,symbols)258 self.append(node)259 if lexer.tok == '(':260 self.parse_error(lexer ,"array of functions" )261 elif lexer.tok == '(':262 lexer.get_token()263 node = Function()264 node.parse(lexer,symbols)265 self.append( node )266 if lexer.tok == '(':267 self.parse_error(lexer ,"function returns a function" )268 if lexer.tok == '[':269 self.parse_error(lexer ,"function returns an array" )270 while stack:271 tok, kind = stack[-1] # peek272 if tok == '(':273 stack.pop()274 self.consume(lexer,')')275 self.parse_declarator(lexer,symbols,stack,level+1)276 elif tok == '*':277 stack.pop()278 self.append( Pointer() )279 else:280 tok, kind = stack.pop()281 self.append( kind )282 if self.verbose:283 print " "*level+"%s.parse_declarator(%s) # <---"%\284 (self,stack)285class AbstractDeclarator(Declarator):286 """ used in ParameterDeclaration; may lack an identifier """287 def parse_identifier(self,lexer,symbols,stack):288 if self.verbose:289 print "%s.parse_identifier()"%self290 ident = None291 ident = Identifier()292 while 1:293 if lexer.tok == ';':294 self.parse_error(lexer)295 if lexer.tok == ')':296 break297 if lexer.tok == ',':298 break299 if lexer.tok == '[':300 break301 if lexer.kind is None:302 #print "%s.new identifier"%self303 ident = Identifier( lexer.tok )304 lexer.get_token()305 #stack.append( (ident.name, ident) )306 break307 stack.append( (lexer.tok, lexer.kind) )308 lexer.get_token()309 if self.verbose:310 print "%s.parse_identifier()=%s"%(self,repr(ident))311 return ident312class FieldLength(Node):313 """314 """315 pass316class StructDeclarator(Declarator):317 """318 """319 def parse(self,lexer,symbols):320 if lexer.tok != ':':321 Declarator.parse(self,lexer,symbols)322 if lexer.tok == ':':323 lexer.get_token()324 # ConstantExpr325 length = int(lexer.tok)326 #print "length = ",length327 self.append( FieldLength(length) )328 lexer.get_token()329class DeclarationSpecifiers(Node,Parser):330 """331 """332 def __init__(self,*items):333 Node.__init__(self,*items)334 def __eq__(self,other):335 " unordered (set/bag) equality "336 if not isinstance(other,Node):337 return 0338 for i in range(len(self)):339 if not self[i] in other:340 return 0341 for i in range(len(other)):342 if not other[i] in self:343 return 0344 return 1345 def parse(self,lexer,symbols):346 self.parse_spec(lexer,symbols)347 self.reverse()348 def parse_spec(self,lexer,symbols):349 typespec = None350 while lexer.tok:351 if isinstance( lexer.kind, TypeAlias ) or\352 isinstance( lexer.kind, BasicType ):353 if typespec is not None:354 self.parse_error(lexer ,"type already specified as %s"\355 %typespec )356 typespec=lexer.kind357 self.append( lexer.kind )358 lexer.get_token()359 elif isinstance( lexer.kind, Qualifier ):360 self.append( lexer.kind )361 lexer.get_token()362 elif isinstance( lexer.kind, StorageClass ):363 self.append( lexer.kind )364 lexer.get_token()365 elif lexer.tok=='struct':366 lexer.get_token()367 self.parse_struct(lexer,symbols)368 break #?369 elif lexer.tok=='union':370 lexer.get_token()371 self.parse_union(lexer,symbols)372 break #?373 elif lexer.tok=='enum':374 lexer.get_token()375 self.parse_enum(lexer,symbols)376 break #?377 elif lexer.kind is None:378 # identifier379 break380 else:381 break382 def parse_struct(self,lexer,symbols):383 if self.verbose:384 print "%s.parse_struct()"%(self)385 node = Struct()386 node.parse(lexer,symbols)387 _node = None388 if node.tag:389 _node = symbols.get_tag( node.tag )390 if _node is not None:391 if not isinstance( _node, Struct ):392 self.parse_error(lexer,"tag defined as wrong kind")393 if len(node)>1:394 if len(_node)>1:395 self.parse_error(lexer,"tag already defined as %s"%_node)396 #symbols.set_tag( node.tag, node )397 #else:398 # refer to the previously defined struct399 ##node = _node400 #node = _node.clone()401 if 0:402 # refer to the previously defined struct403 if len(node)==1:404 _node = symbols.deep_get_tag( node.tag )405 if _node is not None:406 node=_node407 # But what about any future reference to the struct ?408 if node.tag:409 symbols.set_tag( node.tag, node )410 self.append( node )411 def parse_union(self,lexer,symbols):412 if self.verbose:413 print "%s.parse_union(%s)"%(self,node)414 node = Union()415 node.parse(lexer,symbols)416 _node = None417 if node.tag:418 _node = symbols.get_tag( node.tag )419 if _node is not None:420 if not isinstance( _node, Union ):421 self.parse_error(lexer,"tag %s defined as wrong kind"%repr(node.tag))422 if len(node)>1:423 if len(_node)>1:424 self.parse_error(lexer,"tag already defined as %s"%_node)425 #symbols.set_tag( node.tag, node )426 #else:427 #node = _node428 #if len(node)==1:429 #_node = symbols.deep_get_tag( node.tag )430 #if _node is not None:431 #node=_node432 if node.tag:433 symbols.set_tag( node.tag, node )434 self.append( node )435 def parse_enum(self,lexer,symbols):436 if self.verbose:437 print "%s.parse_enum(%s)"%(self,node)438 node = Enum()439 node.parse(lexer,symbols)440 _node = None441 if node.tag:442 _node = symbols.get_tag( node.tag )443 if _node is not None:444 if not isinstance( _node, Enum ):445 self.parse_error(lexer,"tag defined as wrong kind")446 if len(node)>1:447 if len(_node)>1:448 self.parse_error(lexer,"tag already defined as %s"%_node)449 #symbols.set_tag( node.tag, node )450 #else:451 #node = _node452 #if len(node)==1:453 #_node = symbols.deep_get_tag( node.tag )454 #if _node is not None:455 #node=_node456 if node.tag:457 symbols.set_tag( node.tag, node )458 self.append( node )459 def is_typedef(self):460 return self.find(Typedef) is not None461 def needs_declarator(self):462 for node in self:463 if isinstance( node, Struct ):464 return False 465 if isinstance( node, Enum ):466 return False 467 if isinstance( node, Union ):468 return False 469 return True470class TypeSpecifiers(DeclarationSpecifiers):471 " used in ParameterDeclaration "472 def parse_spec(self,lexer,symbols):473 typespec = None474 while lexer.tok:475 if isinstance( lexer.kind, TypeAlias ) or\476 isinstance( lexer.kind, BasicType ):477 if typespec is not None:478 self.parse_error(lexer ,"type already specified as %s"\479 %typespec )480 typespec=lexer.kind481 self.append( lexer.kind )482 lexer.get_token()483 elif isinstance( lexer.kind, Qualifier ):484 self.append( lexer.kind )485 lexer.get_token()486 elif isinstance( lexer.kind, StorageClass ):487 self.parse_error(lexer ,"'%s' cannot appear here"%lexer.tok )488 elif lexer.tok=='struct':489 lexer.get_token()490 self.parse_struct(lexer,symbols)491 break #?492 elif lexer.tok=='union':493 lexer.get_token()494 self.parse_union(lexer,symbols)495 break #?496 elif lexer.tok=='enum':497 lexer.get_token()498 self.parse_enum(lexer,symbols)499 break #?500 elif lexer.kind is None:501 # identifier502 break503 else:504 break505class Initializer(Node,Parser):506 """507 """508 def __init__(self,*items):509 Node.__init__(self,*items)510 def parse(self,lexer,symbols):511 self.parse_error(lexer,"not implemented")512class TypeAlias(Node):513 " typedefed things "514 def __init__(self,name,decl=None):515 Node.__init__(self,name)#,decl)516 self.name=name517 self.decl=decl518class Declaration(Node,Parser):519 """520 """521 def __init__(self,*items):522 Node.__init__(self,*items)523 #self.acted=False524 def parse(self,lexer,symbols):525 if not lexer.tok: 526 return527 Parser.parse_enter(self,lexer)528 declspec = DeclarationSpecifiers() 529 declspec.parse(lexer,symbols)530 if len(declspec)==0:531 if lexer.tok == ';':532 lexer.get_token()533 # empty declaration...534 return535 self.parse_error(lexer,536 "expected specifiers, got '%s'"%lexer.tok )537 self.append(declspec)538 while 1:539 decl = Declarator()540 decl.parse(lexer,symbols)541 if len(decl)==0:542 if declspec.needs_declarator():543 self.parse_error(lexer,544 "expected declarator, got '%s'"%lexer.tok )545 self.append(decl)546 ident = decl.ident547 if ident is not None:548 #if len(ident):549 # install symbol550 node = symbols[ident[0]]551 if node is not None:552 # we allow functions to be defined (as same) again553 #print node.deepstr(),'\n', self.deepstr() 554 _node = node.clone()555 _node.delete(Identifier)556 _self = self.clone()557 _self.delete(Identifier)558 if _node != _self:559 self.parse_error(lexer,560 "\n%s\n already defined as \n%s\n"%\561 (self.deepstr(),node.deepstr()))562 else:563 if self.is_typedef():564 #lexer.mktypedef( ident[0], self )565 tp = TypeAlias(ident[0],decl) 566 lexer.mktypedef( ident[0], tp )567 else:568 symbols[ident[0]] = self569 if lexer.tok == '=':570 # parse initializer571 lexer.get_token()572 init = Initializer()573 init.parse(lexer,symbols)574 ident.append( init ) # as in Enum575 #else: struct, union or enum576 if lexer.tok == ';':577 # no more declarators578 break579 if lexer.tok == '{':580 # ! ahhh, function body !!!581# sys.stderr.write(582# "WARNING: function body found at line %s\n"%lexer.lno )583 bcount = 1584 while bcount:585 lexer.get_brace_token()586 if lexer.tok == '}': 587 bcount -= 1588 if lexer.tok == '{': 589 bcount += 1590 lexer.get_token()591 Parser.parse_leave(self,lexer)592 return593 self.consume(lexer,',')594 self.consume(lexer,';')595 Parser.parse_leave(self,lexer)596 def is_typedef(self):597 spec=self[0]598 assert isinstance(spec,DeclarationSpecifiers), self.deepstr()599 return spec.is_typedef()600class ParameterDeclaration(Declaration):601 """602 """603 def parse(self,lexer,symbols):604 typespec = TypeSpecifiers()605 typespec.parse(lexer,symbols)606 self.append(typespec)607 decl = AbstractDeclarator()608 decl.parse(lexer,symbols)609 self.append(decl)610 ident = decl.ident611 if ident is not None and ident[0]:612 node = symbols[ident[0]]613 if node is not None:614 self.parse_error(lexer,615 "%s already defined as %s"%(ident,node))616 else:617 symbols[ident[0]] = self618class StructDeclaration(Declaration):619 """620 """621 def parse(self,lexer,symbols):622 if not lexer.tok: 623 return624 declspec = DeclarationSpecifiers() 625 declspec.parse(lexer,symbols)626 self.append(declspec)627 if len(declspec)==0:628 if lexer.tok == ';':629 lexer.get_token()630 # empty declaration...631 return632 self.parse_error(lexer,633 "expected specifiers, got '%s'"%lexer.tok )634 while 1:635 decl = StructDeclarator()636 decl.parse(lexer,symbols)637 if len(decl)==0:638 self.parse_error(lexer,639 "expected declarator, got '%s'"%lexer.tok )640 self.append(decl)641 ident = decl.ident642 if ident is not None:643 node = symbols[ident[0]]...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Gherkin-python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful