Best Python code snippet using hypothesis
recipe.py
Source:recipe.py
1import sys2cookbook = {3 "sandwich": (["ham", "bread", "cheese"], "lunch", "10"),4 "cake": (["flour", "sugar", "eggs"], "dessert", "60"),5 "salad": (["avocado", "arugula", "tomatoes", "spinach"], "lunch", "15"),6}7def __clear_screen__():8 print("\033c")9def print_cookbook():10 __clear_screen__()11 print("-" * 64)12 print("The CoookBook contain: " + str(len(cookbook.keys())) + " receipes")13 for recipe in cookbook.keys():14 print("- " + recipe)15 print("\nReceipes informations:")16 for recipe in cookbook.values():17 key = list(cookbook.keys())[list(cookbook.values()).index(recipe)]18 tmp_receipe = recipe[0].__str__().replace(19 "[",20 "").replace(21 "]",22 "").replace(23 "(",24 "").replace(25 ")",26 "").replace(27 "'",28 "")29 time = recipe[1]30 preparation_time = recipe[2]31 print(key)32 print("- Ingredients: " + tmp_receipe)33 print("- Preparation: " + time)34 print("- Time: " + preparation_time + " minutes\n")35 print("-" * 64)36def print_receipe(receipename):37 if not cookbook.keys().__contains__(receipename):38 print("Invalid receipe name")39 return40 print("-" * 64)41 print("Receipe: " + receipename)42 print("Ingredients:")43 for ingredient in cookbook[receipename][0]:44 print("\t- " + ingredient)45 print("Preparation:")46 print("\t- " + cookbook[receipename][1])47 print("Time: " + cookbook[receipename][2] + " minutes")48 print("-" * 64)49def delete_receipe(receipe_index):50 key = list(cookbook.keys())[receipe_index]51 del cookbook[key]52 print("-" * 64)53 print("Receipe deleted !")54 print("-" * 64)55def add_receipe(receipename, ingredients, preparation, time):56 if cookbook.keys().__contains__(receipename):57 __clear_screen__()58 print("\033[1;31;1mError: Receipe already exist\033[0;37;0m")59 return60 cookbook[receipename] = (ingredients, preparation, time)61 print("-" * 64)62 print("Receipe added !")63 print("-" * 64)64def __main__():65 __clear_screen__()66 while (1):67 print("Please select an option by typing the corresponding number:")68 print("1: Add a receipe")69 print("2: Delete a receipe")70 print("3: Print a receipe")71 print("4: Print the CookBook")72 print("5: Quit")73 try:74 print(">> ", end=""),75 sys.stdout.flush()76 value = int(sys.stdin.readline())77 # No ascii option78 except ValueError:79 __clear_screen__()80 print("\033[1;31;1mError: Invalid option\033[0;37;0m")81 continue82 # Add a receipe83 if (value == 1):84 __clear_screen__()85 is_good = False86 while (not is_good):87 print("Enter receipe name:")88 print("> ", end=""),89 sys.stdout.flush()90 receipename = ""91 receipename = str(input())92 receipename.rstrip('\n')93 if (str(len(receipename)) == 0 or not receipename.isalpha()):94 __clear_screen__()95 print("\033[1;31;1mError: \96Invalid receipe name\033[0;37;0m")97 continue98 else:99 is_good = True100 is_good = False101 __clear_screen__()102 while (not is_good):103 print("Enter ingredients (use , to separate them):")104 print("> ", end=""),105 array_ingredients = []106 sys.stdout.flush()107 ingredients = ""108 ingredients = str(input())109 ingredients.rstrip('\n')110 for char in ingredients:111 if char == ' ':112 ingredients = ingredients.replace(char, "")113 if (str(len(ingredients)) == 0 or ingredients in "0123456789"):114 __clear_screen__()115 print("\033[1;31;1mError: Invalid ingredients\033[0;37;0m")116 continue117 else:118 array_ingredients = ingredients.split(",")119 is_good = True120 is_good = False121 __clear_screen__()122 while (not is_good):123 print("Enter preparation:")124 print("> ", end=""),125 sys.stdout.flush()126 preparation = ""127 preparation = str(input())128 preparation.rstrip('\n')129 if (str(len(preparation)) == 0 or not preparation.isalpha()):130 __clear_screen__()131 print("\033[1;31;1mError: Invalid preparation\033[0;37;0m")132 continue133 else:134 is_good = True135 is_good = False136 __clear_screen__()137 while (not is_good):138 print("Enter time:")139 print("> ", end=""),140 sys.stdout.flush()141 time = ""142 time = str(input())143 time.rstrip('\n')144 if (str(len(time)) == 0 or not time.isdigit()145 or int(time) <= 0):146 __clear_screen__()147 print("\033[1;31;1mError: Invalid time\033[0;37;0m")148 continue149 else:150 is_good = True151 add_receipe(receipename, array_ingredients, preparation, time)152 # Delete a receipe153 elif (value == 2):154 __clear_screen__()155 is_good = False156 if (len(cookbook.keys()) == 0):157 print("\033[1;31;1mError: CookBook is empty\033[0;37;0m")158 continue159 while (not is_good):160 print("Select a receipe:")161 for recipe in cookbook.keys():162 index = list(cookbook.keys()).index(recipe) + 1163 print(" - " + index.__str__() + ": " + recipe)164 print("> ", end=""),165 sys.stdout.flush()166 try:167 receipe_index = int(sys.stdin.readline())168 if (receipe_index > 0 and receipe_index <=169 len(cookbook.keys())):170 is_good = True171 else:172 __clear_screen__()173 print("\033[1;31;1mError: Invalid option\033[0;37;0m")174 except ValueError:175 __clear_screen__()176 print("\033[1;31;1mError: Invalid option\033[0;37;0m")177 delete_receipe(receipe_index - 1)178 # Print a receipe179 elif (value == 3):180 __clear_screen__()181 is_good = False182 if (len(cookbook.keys()) == 0):183 print("\033[1;31;1mError: CookBook is empty\033[0;37;0m")184 continue185 while (not is_good):186 print("Select a receipe:")187 for recipe in cookbook.keys():188 index = list(cookbook.keys()).index(recipe) + 1189 print(" - " + index.__str__() + ": " + recipe)190 print("> ", end=""),191 sys.stdout.flush()192 receipename = sys.stdin.readline()193 try:194 receipename = int(receipename)195 if (receipename > 0 and receipename196 <= len(cookbook.keys())):197 is_good = True198 else:199 __clear_screen__()200 print("\033[1;31;1mError: Invalid option\033[0;37;0m")201 except ValueError:202 __clear_screen__()203 print("\033[1;31;1mError: Invalid option\033[0;37;0m")204 __clear_screen__()205 print_receipe(list(cookbook.keys())[receipename - 1])206 continue207 # Print the cookbook208 elif (value == 4):209 print_cookbook()210 # Quit the cookbook211 elif (value == 5):212 __clear_screen__()213 print("Cookbook closed")214 break215 # Invalid Options < 1 || > 5216 else:217 __clear_screen__()218 print(219 "\033[1;31;1mError: This option does not exist, \220please type the corresponding number.\033[0;37;0m")221 continue...
instanciate.py
Source:instanciate.py
...22 def read(self):23 vals = self.server.read(self.params)24 new_vals = []25 for idx, val in enumerate(vals):26 if not val.StatusCode.is_good():27 print(val)28 print("Error attribute %s is not valid for node %s" % (self._debug_attr[idx], self.nodeid))29 # val.StatusCode.check()30 new_vals.append(val.Value.Value)31 return new_vals32# def _read_attributed(server, nodeid, attrs_obj, *attrs):33 #ra = _ReadAdder(server, rdesc.NodeId)34 # for attr in attrs:35 # ra.add(atttr)36 #vals = ra.read()37def instanciate_node(parent, node_type, idx):38 """39 Instanciate a new node under 'parent' using a type40 """41 results = node_type.get_attributes([ua.AttributeIds.NodeClass, ua.AttributeIds.BrowseName, ua.AttributeIds.DisplayName])42 nclass, bname, dname = [res.Value.Value for res in results]43 #descs = node_type.get_children_descriptions(refs=ua.ObjectIds.HasTypeDefinition)44 typedef = ua.FourByteNodeId(ua.ObjectIds.BaseObjectType)45 # if len(descs) > 1:46 #print("DESCS", descs)47 #typedef = descs[0].TypeDefinition48 rdesc = ua.ReferenceDescription()49 rdesc.NodeId = node_type.nodeid50 rdesc.BrowseName = bname51 rdesc.DisplayName = dname52 rdesc.NodeClass = nclass53 rdesc.ReferenceTypeId = ua.TwoByteNodeId(ua.ObjectIds.HasComponent)54 rdesc.TypeDefinition = typedef55 print("MYRDESC", rdesc)56 return _instanciate_node(parent.server, parent.nodeid, rdesc, idx)57def _instanciate_node(server, parentid, rdesc, idx):58 """59 Instanciate a new node under 'parent' using a type60 """61 print("Instanciating: node %s in %s" % (rdesc, parentid))62 addnode = ua.AddNodesItem()63 addnode.RequestedNewNodeId = ua.NodeId()64 addnode.BrowseName = rdesc.BrowseName65 addnode.NodeClass = rdesc.NodeClass66 addnode.ParentNodeId = parentid67 addnode.ReferenceTypeId = ua.TwoByteNodeId(ua.ObjectIds.HasComponent)68 addnode.TypeDefinition = rdesc.TypeDefinition69 print("ADDNODE", addnode)70 node_type = Node(server, rdesc.NodeId)71 if rdesc.NodeClass in (ua.NodeClass.Object, ua.NodeClass.ObjectType):72 print(node_type, " is object")73 _read_and_copy_attrs(node_type, ua.ObjectAttributes(), addnode)74 #_add_object_attrs(addnode, rdesc, node_type)75 elif rdesc.NodeClass in (ua.NodeClass.Variable, ua.NodeClass.VariableType):76 print(node_type, " is variable")77 _read_and_copy_attrs(node_type, ua.VariableAttributes(), addnode)78 #_add_variable_attrs(addnode, rdesc, node_type)79 else:80 print("Node class not supported: ", rdesc.NodeClass)81 print("ADDNODE FINAL ", addnode)82 server.add_nodes([addnode])83 refs = []84 ref = ua.AddReferencesItem()85 ref.IsForward = True86 ref.ReferenceTypeId = addnode.ReferenceTypeId87 ref.SourceNodeId = parentid88 ref.TargetNodeClass = addnode.NodeClass89 ref.TargetNodeId = addnode.RequestedNewNodeId90 refs.append(ref)91 server.add_references(refs)92 descs = node_type.get_children_descriptions(includesubtypes=False) # FIXME: should be false93 print("node is", rdesc.NodeId, node_type, node_type.get_children())94 print("Children are: ", descs)95 for rdesc in descs:96 _instanciate_node(server, addnode.RequestedNewNodeId, rdesc, idx)97 return Node(server, addnode.RequestedNewNodeId)98def _add_object_attrs(addnode, node_type):99 results = node_type.get_attributes([100 ua.AttributeIds.BrowseName,101 ua.AttributeIds.Description,102 ua.AttributeIds.WriteMask,103 ua.AttributeIds.UserWriteMask,104 ua.AttributeIds.EventNotifier])105 attrs = ua.ObjectAttributes()106 _set_attr(attrs.DisplayName, results, 0)107 _set_attr(attrs.Description, results, 0)108 attrs.DisplayName = rdesc.BrowseName109 attrs.Description = rdesc.Description110 if results[0].StatusCode.is_good():111 attrs.Description = results[0].Value.Value112 if results[1].StatusCode.is_good():113 attrs.WriteMask = results[1].Value.Value114 if results[2].StatusCode.is_good():115 attrs.UserWriteMask = results[2].Value.Value116 if results[3].StatusCode.is_good():117 attrs.UserWriteMask = results[3].Value.Value118 addnode.NodeAttributes = attrs119def _read_and_copy_attrs(node_type, struct, addnode):120 names = [name for name in struct.__dict__.keys() if not name.startswith("_") and name not in ("BodyLength", "TypeId", "SpecifiedAttributes", "Encoding")]121 attrs = [getattr(ua.AttributeIds, name) for name in names]122 print("Names are ", names)123 for name in names:124 results = node_type.get_attributes(attrs)125 for idx, name in enumerate(names):126 if results[idx].StatusCode.is_good():127 if name == "Value":128 setattr(struct, name, results[idx].Value)129 else:130 setattr(struct, name, results[idx].Value.Value)131 else:132 print("!!!!!!!!!!!!Error, for nodeid %s, attribute %s, statuscode is %s" % (node_type, name, results[idx].StatusCode))133 print("struct is ", struct)134 addnode.NodeAttributes = struct135def _add_variable_attrs(addnode, rdesc, node_type):136 results = node_type.get_attributes([137 ua.AttributeIds.EventNotifier,138 ua.AttributeIds.Description,139 ua.AttributeIds.WriteMask,140 ua.AttributeIds.UserWriteMask,141 ua.AttributeIds.Value,142 ua.AttributeIds.DataType,143 ua.AttributeIds.ValueRank,144 ua.AttributeIds.ArrayDimentions,145 ua.AttributeIds.AccessLevel,146 ua.AttributeIds.UserAccessLevel,147 ua.AttributeIds.MinimumSamplingInterval,148 ua.AttributeIds.Historizing])149 attrs = ua.ObjectAttributes()150 if results[0].is_good():151 attrs.DisplayName = results[0].Value.Value152 if results[1].is_good():153 attrs.Description = results[1].Value.Value154 if results[2].is_good():155 attrs.WriteMask = results[2].Value.Value156 if results[3].is_good():157 attrs.UserWriteMask = results[3].Value.Value158 # if results[4].is_good():159 #attrs.Value = results[4].Value.Value160 if results[5].is_good():161 attrs.DataType = results[5].Value.Value162 if results[6].is_good():163 attrs.ValueRank = results[6].Value.Value164 if results[7].is_good():165 attrs.ArrayDimensions = results[7].Value.Value166 if results[8].is_good():167 attrs.AccessLevel = results[8].Value.Value168 if results[9].is_good():169 attrs.UserAccessLevel = results[9].Value.Value170 if results[10].is_good():171 attrs.MinimumSamplingInterval = results[10].Value.Value172 if results[11].is_good():173 attrs.Historizing = results[11].Value.Value174 addnode.NodeAttributes = attrs175def _set_attr(container, result, idx):176 if result.is_good():...
validate_account_toml.py
Source:validate_account_toml.py
1import argparse2from pathlib import Path3try:4 import toml5except ImportError:6 print("toml package not available.")7 print("Install with `python3 -m pip install toml`.")8 exit(1)9from validate import is_valid_key10def parse_args():11 def file_path(path):12 if not Path(path).is_file():13 raise argparse.ArgumentTypeError(f'{path} is not a valid file.')14 if not Path(path).exists():15 raise argparse.ArgumentTypeError(f'{path} does not exist.')16 return Path(path)17 parser = argparse.ArgumentParser(description='Convert csv files to accounts.toml.')18 parser.add_argument('accounts_toml_path', type=file_path, help="Path to accounts.toml file")19 return parser.parse_args()20def is_int(value):21 try:22 _ = int(value)23 except ValueError:24 return False25 else:26 return True27def is_valid(toml_obj):28 is_good = True29 for key in toml_obj.keys():30 if key not in ("accounts", "delegators"):31 print(f"ERR: Unknown root level group: {key}")32 is_good = False33 accounts = toml_obj.get("accounts", None)34 delegators = toml_obj.get("delegators", None)35 if accounts is None:36 print("ERR: No accounts found.")37 is_good = False38 if delegators is None:39 print("WARN: No delegators found.")40 account_keys = []41 validator_keys = []42 total_amt = 043 for account in accounts:44 account_key = account.get("public_key", None)45 account_balance = account.get("balance", None)46 validator = account.get("validator", None)47 if validator is None:48 account_bonded_amount, account_delegation_rate = None, None49 else:50 account_bonded_amount = validator.get("bonded_amount", None)51 account_delegation_rate = validator.get("delegation_rate", None)52 if account_key is None:53 print("ERR: Missing accounts.public_key")54 is_good = False55 elif not is_valid_key(account_key):56 print(f"ERR: Invalid accounts.public_key: {account_key}")57 is_good = False58 elif account_key in account_keys:59 print(f"ERR: Duplicated account_key: {account_key}")60 is_good = False61 else:62 account_keys.append(account_key)63 if account_balance is None:64 print("ERR: Missing accounts.balance")65 is_good = False66 elif not is_int(account_balance):67 print(f"ERR: Invalid accounts.balance: {account_balance} for {account_key}")68 is_good = False69 else:70 total_amt += int(account_balance)71 if account_bonded_amount is not None or account_delegation_rate is not None:72 validator_keys.append(account_key)73 if account_bonded_amount is None:74 print(f"ERR: No bonded_amount with delegation_rate for {account_key}")75 is_good = False76 elif not is_int(account_bonded_amount):77 print(f"ERR: Invalid bonded_amount for {account_key}")78 is_good = False79 else:80 total_amt += int(account_bonded_amount)81 if account_delegation_rate is None:82 print(f"ERR: No delegation_rate with bonded_amount for {account_key}")83 is_good = False84 elif not is_int(account_delegation_rate):85 print(f"ERR: Invalid delegation_rate for {account_key}")86 is_good = False87 elif int(account_delegation_rate) < 0 or int(account_delegation_rate) > 100:88 print(f"ERR: delegation_rate not between 0 and 100 for {account_key}")89 is_good = False90 delegator_keys = []91 for delegator in delegators:92 validator_key = delegator.get("validator_public_key", None)93 delegator_key = delegator.get("delegator_public_key", None)94 balance = delegator.get("balance", None)95 delegated_amount = delegator.get("delegated_amount", None)96 if validator_key is None:97 print(f"ERR: Missing validator_key for delegator_key: {delegator_key}")98 is_good = False99 elif not is_valid_key(validator_key):100 print(f"ERR: Invalid validator_key: {validator_key}")101 is_good = False102 elif validator_key not in validator_keys:103 print(f"ERR: Cannot delegate to unknown validator_key: {validator_key}")104 is_good = False105 if delegator_key is None:106 print(f"ERR: Missing delegator_key with validator_key: {validator_key}")107 is_good = False108 elif not is_valid_key(delegator_key):109 print(f"ERR: Invalid delegator_key: {delegator_key}")110 is_good = False111 elif delegator_key in delegator_keys:112 print(f"ERR: Duplicate delegator_key: {delegator_key}")113 is_good = False114 else:115 delegator_keys.append(delegator_key)116 if balance is None:117 print(f"ERR: No balance with delegator_key: {delegator_key}")118 is_good = False119 elif not is_int(balance):120 print(f"ERR: Invalid balance with delegator_key: {delegator_key}")121 is_good = False122 else:123 total_amt += int(balance)124 if delegated_amount is None:125 print(f"ERR: No delegated_amount with delegator_key: {delegator_key}")126 is_good = False127 elif not is_int(delegated_amount):128 print(f"ERR: Invalid delegated_amount with delegator_key: {delegator_key}")129 is_good = False130 else:131 total_amt += int(delegated_amount)132 if is_good:133 print(f"Total Amt: {total_amt}")134 return is_good135if __name__ == '__main__':136 args = parse_args()137 toml_obj = toml.load(args.accounts_toml_path)138 if is_valid(toml_obj):...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!