Best Python code snippet using hypothesis
parse.py
Source:parse.py
...92 content.remarks = parsed_file93 return content94def raw_to_unit_cell_messy(parsed_object, cell):95 prefix = "_cell_"96 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [cell_length_a]))97 if (valid_key != None):98 cell.length_a = get_uncertain_float(parsed_object, valid_key)99 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [cell_length_b]))100 if (valid_key != None):101 cell.length_b = get_uncertain_float(parsed_object, valid_key)102 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [cell_length_c]))103 if (valid_key != None):104 cell.length_c = get_uncertain_float(parsed_object, valid_key)105 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [cell_angle_alpha]))106 if (valid_key != None):107 cell.angle_alpha = get_uncertain_float(parsed_object, valid_key)108 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [cell_angle_beta]))109 if (valid_key != None):110 cell.angle_beta = get_uncertain_float(parsed_object, valid_key)111 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [cell_angle_gamma]))112 if (valid_key != None):113 cell.angle_gamma = get_uncertain_float(parsed_object, valid_key)114# converts raw data to formatted atom for files without categories.115def raw_to_atom_messy(parsed_object):116 prefix = atoms_key + "_"117 atom = Content.Atom()118 is_atom = False119 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [atom_symbol_key]))120 if (valid_key != None):121 is_atom = True122 atom.symbol = get_string(parsed_object, valid_key)123 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [atom_serial_key]))124 if (valid_key != None):125 is_atom = True126 atom.atom_serial = get_int(parsed_object, valid_key)127 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, atom_name_key))128 if (valid_key != None):129 is_atom = True130 atom.atom_name = get_string(parsed_object, valid_key)131 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [atom_residue_serial_key]))132 if (valid_key != None):133 is_atom = True134 atom.residue_serial = get_int(parsed_object, valid_key)135 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [atom_residue_name_key]))136 if (valid_key != None):137 is_atom = True138 atom.residue_name = get_string(parsed_object, valid_key)139 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [atom_chain_key]))140 if (valid_key != None):141 is_atom = True142 atom.chain = get_string(parsed_object, valid_key)143 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, atom_x_key))144 if (valid_key != None):145 is_atom = True146 atom.x = get_uncertain_float(parsed_object, valid_key)147 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, atom_y_key))148 if (valid_key != None):149 is_atom = True150 atom.y = get_uncertain_float(parsed_object, valid_key)151 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, atom_z_key))152 if (valid_key != None):153 is_atom = True154 atom.z = get_uncertain_float(parsed_object, valid_key)155 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [atom_occupancy_key]))156 if (valid_key != None):157 is_atom = True158 atom.occupancy = get_uncertain_float(parsed_object, valid_key)159 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [atom_bfactor_key]))160 if (valid_key != None):161 is_atom = True162 atom.bfactor = get_uncertain_float(parsed_object, valid_key)163 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [atom_model_key]))164 if (valid_key != None):165 is_atom = True166 atom.model = get_int(parsed_object, valid_key)167 valid_key = get_valid_key(parsed_object, prefix_keys(prefix, [atom_type_key]))168 if (valid_key != None):169 type = get_string(parsed_object, valid_key)170 if (type == "ATOM"):171 atom.is_het = False172 if (type == "HETATM"):173 atom.is_het = True174 isCart = get_valid_key(parsed_object, prefix_keys(prefix, ["fract_x"])) == None175 atom.fract = not isCart176 if (not is_atom):177 return None178 return atom179def raw_to_atom(parsed_object):180 try:181 atom = Content.Atom()182 valid_key = get_valid_key(parsed_object, [atom_symbol_key])183 if (valid_key != None):184 atom.symbol = get_string(parsed_object, valid_key)185 valid_key = get_valid_key(parsed_object, [atom_serial_key])186 if (valid_key != None):187 atom.atom_serial = get_int(parsed_object, valid_key)188 valid_key = get_valid_key(parsed_object, atom_name_key)189 if (valid_key != None):190 atom.atom_name = get_string(parsed_object, valid_key)191 valid_key = get_valid_key(parsed_object, [atom_residue_serial_key])192 if (valid_key != None):193 atom.residue_serial = get_int(parsed_object, valid_key)194 valid_key = get_valid_key(parsed_object, [atom_residue_name_key])195 if (valid_key != None):196 atom.residue_name = get_string(parsed_object, valid_key)197 valid_key = get_valid_key(parsed_object, [atom_chain_key])198 if (valid_key != None):199 atom.chain = get_string(parsed_object, valid_key)200 valid_key = get_valid_key(parsed_object, atom_x_key)201 if (valid_key != None):202 atom.x = get_float(parsed_object, valid_key)203 valid_key = get_valid_key(parsed_object, atom_y_key)204 if (valid_key != None):205 atom.y = get_float(parsed_object, valid_key)206 valid_key = get_valid_key(parsed_object, atom_z_key)207 if (valid_key != None):208 atom.z = get_float(parsed_object, valid_key)209 valid_key = get_valid_key(parsed_object, [atom_occupancy_key])210 if (valid_key != None):211 atom.occupancy = get_float(parsed_object, valid_key)212 valid_key = get_valid_key(parsed_object, [atom_bfactor_key])213 if (valid_key != None):214 atom.bfactor = get_float(parsed_object, valid_key)215 valid_key = get_valid_key(parsed_object, [atom_model_key])216 if (valid_key != None):217 atom.model = get_int(parsed_object, valid_key)218 valid_key = get_valid_key(parsed_object, [atom_type_key])219 if (valid_key != None):220 type = get_string(parsed_object, valid_key)221 if (type == "ATOM"):222 atom.is_het = False223 if (type == "HETATM"):224 atom.is_het = True225 isCart = get_valid_key(parsed_object, "fract_x") == None226 atom.fract = not isCart227 return atom228 except:229 Logs.error("Error while parsing MMCIF atom")230 raise231# Parsing the file232def ParseLines(lines):233 parsed_file = {}234 # find first field235 lines.move_next_val()236 while not lines.isEnd():237 try:238 section_objects, category = parse_category(lines)239 if (category != None and section_objects != None):240 if category in parsed_file:241 parsed_file[category] += section_objects242 else:243 parsed_file[category] = section_objects244 except Exception:245 Logs.warning("Problem during parsing, skipping line. Error on line:", lines.get_line_number())246 Logs.warning(traceback.format_exc())247 lines.move_next()248 return parsed_file249def parse_category(lines):250 sections_objects = None251 category = None252 lines.move_next_val()253 if not lines.isEnd():254 line = lines.get_line()255 if (is_loop_header(line)):256 lines.move_next()257 sections_objects, category = parse_loop(lines)258 elif (is_definition(line)):259 sections_objects, category = parse_single_val(lines)260 else:261 lines.move_next()262 return sections_objects, category263def parse_loop(lines):264 keys = []265 parsed_objects = []266 category = None267 # Get all the keys268 while not lines.isEnd():269 line = lines.get_line()270 if not is_definition(line):271 break272 category, key, value = get_data_category(line)273 keys.append(key)274 lines.move_next()275 # Read values and pair them with keys276 while not lines.isEnd():277 try:278 parsed_object = {}279 line = lines.get_line()280 if (is_empty(line)):281 lines.move_next()282 continue283 if (is_section_starter(line) or284 is_comment(line)):285 break286 lines.move_next()287 splits = split_line(line) # split by whitespace288 while (len(splits) < len(keys)): # multi-line case289 line = lines.get_line()290 lines.move_next()291 splits += split_line(line)292 for i in range(len(keys)): # pair keys with line values293 key = keys[i]294 value = splits[i]295 parsed_object[key] = value296 parsed_objects.append(parsed_object)297 except:298 Logs.debug("MMCIF_Parsing")299 raise300 return parsed_objects, category301def parse_single_val(lines):302 parsed_objects = []303 line = lines.get_line()304 lines.move_next()305 category, key, value = get_data_category(line)306 if (value == None): # value is on next line307 line = lines.get_line()308 # input is multi-line. gotta read lines until we see another ';'309 if is_multiline(line):310 value = compose_multiline_val(lines)311 # input is exactly 2 lines312 else:313 lines.move_next()314 value = line315 section_object = {}316 section_object[key] = value317 parsed_objects.append(section_object)318 return parsed_objects, category319# reads a multiline value and composes it into a single string320def compose_multiline_val(lines):321 max_lines = 10322 starting_line_number = lines.get_line_number()323 line = lines.get_line()324 lines.move_next()325 multi_line = record_chunk_string(line, 2)326 while not lines.isEnd():327 line = lines.get_line()328 lines.move_next()329 if is_multiline(line):330 break331 else:332 multi_line += line333 # Prevent unclosed multi-lines from breaking everything.334 if (lines.get_line_number() - starting_line_number > max_lines):335 lines.set_line_number(starting_line_number)336 # It will try reading each line (and fail) until it leaves the broken section.337 raise Exception("Multi-line field excedes max number of lines (" + str(max_lines) + ")")338 return multi_line339# region line checkers340def is_section_starter(line):341 return (is_loop_header(line) or is_definition(line))342def is_loop_header(line):343 first_five = record_chunk_string(line, 1, 5)344 return (first_five == "loop_")345def is_definition(line):346 first_val = record_chunk_string(line, 1, 1)347 return (first_val == "_")348def is_comment(line):349 first_val = record_chunk_string(line, 1, 1)350 return (first_val == "#")351def is_multiline(line):352 first_val = record_chunk_string(line, 1, 1)353 return (first_val == ";")354def is_empty(line):355 return (line == "")356# endregion357# Tools for parsing strings358# return the string from start to end position after excluding the white space359def record_chunk_string(line, start=1, end=2147483647):360 true_start = start - 1361 true_end = min(end, len(line))362 return line[true_start:true_end].strip()363# captures "<category>.<key> <value> "364# there must be some whitespace between <key> and <value> and there can be any amount of whitespace at the end.365# category is 1 word and optional,366# key is 1 word367# and the value can be either 1 word or any number of words wrapped in single quotes.368category_regex = re.compile(r"^(?:([^\s]+)\.)?([^\s]+)(?:\s+((?:[^\s]*)|(?:\'.*\')))?\s*$")369def get_data_category(line):370 match = re.match(category_regex, line)371 if (match == None):372 Logs.error(line)373 return374 category = match.group(1)375 key = match.group(2)376 value = match.group(3)377 if category == None:378 category = "Misc"379 return category, key, value380# splits item by space, except for those contained by quotes381split_regex = re.compile(r"(['\"])(.+?)\1|([^\s]+)")382def split_line(line):383 groups = re.findall(split_regex, line)384 result = []385 for group in groups:386 if not group[1] == "":387 result.append(group[1])388 else:389 result.append(group[2])390 return result391# Tools for reading values from the Parsed Objects392def get_valid_key(obj, keys):393 for key in keys:394 if (key in obj):395 return key396 return None397def get_string(obj, key):398 return obj[key]399def get_int(obj, key):400 return int(obj[key])401def get_float(obj, key):402 return float(obj[key])403# Tools for reading poorly formatted values from Parsed Objects404def prefix_keys(prefix, keys):405 new_keys = []406 for key in keys:...
test_validators.py
Source:test_validators.py
1from django.core.exceptions import ValidationError2from awx.main.validators import (3 validate_private_key,4 validate_certificate,5 validate_ssh_private_key,6 vars_validate_or_raise,7)8from awx.main.tests.data.ssh import (9 TEST_SSH_RSA1_KEY_DATA,10 TEST_SSH_KEY_DATA,11 TEST_SSH_KEY_DATA_LOCKED,12 TEST_OPENSSH_KEY_DATA,13 TEST_OPENSSH_KEY_DATA_LOCKED,14 TEST_SSH_CERT_KEY,15 TEST_CATTED_SSH_KEY_DATA,16)17from rest_framework.serializers import ValidationError as RestValidationError18import pytest19def test_invalid_keys():20 invalid_keys = [21 "---BEGIN FOO -----foobar-----END FOO----",22 "-----BEGIN FOO---foobar-----END FOO----",23 "-----BEGIN FOO-----foobar---END FOO----",24 "----- BEGIN FOO ----- foobar ----- FAIL FOO ----",25 "----- FAIL FOO ----- foobar ----- END FOO ----",26 "----BEGIN FOO----foobar----END BAR----",27 ]28 for invalid_key in invalid_keys:29 with pytest.raises(ValidationError):30 validate_private_key(invalid_key)31 with pytest.raises(ValidationError):32 validate_certificate(invalid_key)33 with pytest.raises(ValidationError):34 validate_ssh_private_key(invalid_key)35def test_invalid_rsa_key():36 invalid_key = TEST_SSH_KEY_DATA.replace('-----END', '----END')37 with pytest.raises(ValidationError):38 validate_private_key(invalid_key)39 with pytest.raises(ValidationError):40 validate_certificate(invalid_key)41 with pytest.raises(ValidationError):42 validate_ssh_private_key(invalid_key)43def test_valid_catted_rsa_key():44 valid_key = TEST_CATTED_SSH_KEY_DATA45 pem_objects = validate_private_key(valid_key)46 assert pem_objects[0]['key_type'] == 'rsa'47 assert not pem_objects[0]['key_enc']48 with pytest.raises(ValidationError):49 validate_certificate(valid_key)50 pem_objects = validate_ssh_private_key(valid_key)51 assert pem_objects[0]['key_type'] == 'rsa'52 assert not pem_objects[0]['key_enc']53def test_valid_rsa_key():54 valid_key = TEST_SSH_KEY_DATA55 pem_objects = validate_private_key(valid_key)56 assert pem_objects[0]['key_type'] == 'rsa'57 assert not pem_objects[0]['key_enc']58 with pytest.raises(ValidationError):59 validate_certificate(valid_key)60 pem_objects = validate_ssh_private_key(valid_key)61 assert pem_objects[0]['key_type'] == 'rsa'62 assert not pem_objects[0]['key_enc']63def test_valid_locked_rsa_key():64 valid_key = TEST_SSH_KEY_DATA_LOCKED65 pem_objects = validate_private_key(valid_key)66 assert pem_objects[0]['key_type'] == 'rsa'67 assert pem_objects[0]['key_enc']68 with pytest.raises(ValidationError):69 validate_certificate(valid_key)70 pem_objects = validate_ssh_private_key(valid_key)71 assert pem_objects[0]['key_type'] == 'rsa'72 assert pem_objects[0]['key_enc']73def test_valid_openssh_key():74 valid_key = TEST_OPENSSH_KEY_DATA75 pem_objects = validate_private_key(valid_key)76 assert pem_objects[0]['key_type'] == 'ed25519'77 assert not pem_objects[0]['key_enc']78 with pytest.raises(ValidationError):79 validate_certificate(valid_key)80 pem_objects = validate_ssh_private_key(valid_key)81 assert pem_objects[0]['key_type'] == 'ed25519'82 assert not pem_objects[0]['key_enc']83def test_valid_locked_openssh_key():84 valid_key = TEST_OPENSSH_KEY_DATA_LOCKED85 pem_objects = validate_private_key(valid_key)86 assert pem_objects[0]['key_type'] == 'ed25519'87 assert pem_objects[0]['key_enc']88 with pytest.raises(ValidationError):89 validate_certificate(valid_key)90 pem_objects = validate_ssh_private_key(valid_key)91 assert pem_objects[0]['key_type'] == 'ed25519'92 assert pem_objects[0]['key_enc']93def test_valid_rsa1_key():94 valid_key = TEST_SSH_RSA1_KEY_DATA95 pem_objects = validate_ssh_private_key(valid_key)96 assert pem_objects[0]['key_type'] == 'rsa1'97 assert not pem_objects[0]['key_enc']98 with pytest.raises(ValidationError):99 validate_certificate(valid_key)100 pem_objects = validate_ssh_private_key(valid_key)101 assert pem_objects[0]['key_type'] == 'rsa1'102 assert not pem_objects[0]['key_enc']103def test_cert_with_key():104 cert_with_key = TEST_SSH_CERT_KEY105 with pytest.raises(ValidationError):106 validate_private_key(cert_with_key)107 with pytest.raises(ValidationError):108 validate_certificate(cert_with_key)109 pem_objects = validate_ssh_private_key(cert_with_key)110 assert pem_objects[0]['type'] == 'CERTIFICATE'111 assert pem_objects[1]['key_type'] == 'rsa'112 assert not pem_objects[1]['key_enc']113@pytest.mark.parametrize("var_str", [114 '{"a": "b"}',115 '---\na: b\nc: d',116 '',117 '""',118])119def test_valid_vars(var_str):120 vars_validate_or_raise(var_str)121@pytest.mark.parametrize("var_str", [122 '["a": "b"]',123 '["a", "b"]',124 "('a=4', 'c=5')",125 '"',126 "''",127 "5",128 "6.74",129 "hello",130 "OrderedDict([('a', 'b')])",131 "True",132 "False",133])134def test_invalid_vars(var_str):135 with pytest.raises(RestValidationError):...
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!!