Best Python code snippet using avocado_python
config_change_validation.py
Source:config_change_validation.py
...6"""7import commands8import os9import shutil10def get_temp_file_path(file_path):11 """12 Generates a temporary filename13 """14 return file_path + '.tmp'15def make_temp_file_copies(file_paths):16 """17 Creates temporary copies of the provided files18 """19 for file_path in file_paths:20 temp_file_path = get_temp_file_path(file_path)21 shutil.copyfile(file_path, temp_file_path)22def del_temp_file_copies(file_paths):23 """24 Deletes all the provided files25 """26 for file_path in file_paths:27 temp_file_path = get_temp_file_path(file_path)28 os.remove(temp_file_path)29def parse_unified_diff_output(lines):30 """31 Parses the unified diff output of two files32 Returns a pair of adds and removes, where each is a list of trimmed lines33 """34 adds = []35 removes = []36 for line in lines:37 # ignore filepaths in the output38 if (len(line) > 2 and39 (line[:3] == "+++" or40 line[:3] == "---")):41 continue42 # ignore line range information in the output43 elif len(line) > 1 and line[:2] == "@@":44 continue45 # gather adds46 elif len(line) > 0 and line[0] == "+":47 added_line = line[1:].lstrip().rstrip()48 if len(added_line) == 0:49 continue50 adds = adds + [added_line]51 # gather removes52 elif len(line) > 0 and line[0] == "-":53 removed_line = line[1:].lstrip().rstrip()54 if len(removed_line) == 0:55 continue56 removes = removes + [removed_line]57 return (adds, removes)58def extract_config_changes(file_paths, compared_file_paths=[]):59 """60 Extracts diff information based on the new and61 temporarily saved old config files62 Returns a dictionary of file path and corresponding63 diff information key-value pairs.64 """65 changes = {}66 for i in range(len(file_paths)):67 temp_file_path = get_temp_file_path(file_paths[i])68 if len(compared_file_paths) > i:69 command = ("diff -U 0 -b " + compared_file_paths[i] + " " +70 file_paths[i])71 else:72 command = "diff -U 0 -b " + temp_file_path + " " + file_paths[i]73 (_, output) = commands.getstatusoutput(command)74 lines = output.split('\n')75 changes[file_paths[i]] = parse_unified_diff_output(lines)76 return changes77def assert_config_change_dict(actual_result, expected_result):78 """79 Calculates unexpected line changes.80 The arguments actual_result and expected_results are of81 the same data structure type: Dict[file_path] --> (adds, removes),82 where adds = [added_line, ...] and removes = [removed_line, ...].83 The return value has the following structure:84 Dict[file_path] --> (unexpected_adds,85 not_present_adds,86 unexpected_removes,87 not_present_removes)88 """89 change_diffs = {}90 for file_path, actual_changes in actual_result.items():91 expected_changes = expected_result[file_path]92 actual_adds = actual_changes[0]93 actual_removes = actual_changes[1]94 expected_adds = expected_changes[0]95 expected_removes = expected_changes[1]96 # Additional unexpected adds -- they should have been not added97 unexpected_adds = sorted(set(actual_adds) - set(expected_adds))98 # Not present expected adds -- they should have been added99 not_present_adds = sorted(set(expected_adds) - set(actual_adds))100 # Additional unexpected removes - they should have been not removed101 unexpected_removes = sorted(set(actual_removes) - set(expected_removes))102 # Not present expected removes - they should have been removed103 not_present_removes = sorted(set(expected_removes) -104 set(actual_removes))105 change_diffs[file_path] = (unexpected_adds, not_present_adds,106 unexpected_removes, not_present_removes)107 return change_diffs108def assert_config_change(actual_result, expected_result):109 """110 Wrapper of the upper method returning boolean true if no config changes111 were detected.112 """113 change_diffs = assert_config_change_dict(actual_result, expected_result)114 for file_change in change_diffs.values():115 for line_change in file_change:116 if len(line_change) != 0:117 return False118 return True119def print_change_diffs(change_diffs):120 """121 Pretty prints the output of the evaluate_config_changes function122 """123 diff_strings = []124 for file_path, change_diff in change_diffs.items():125 if not (change_diff[0] or change_diff[1] or126 change_diff[2] or change_diff[3]):127 continue128 diff_strings.append("--- %s" % get_temp_file_path(file_path))129 diff_strings.append("+++ %s" % file_path)130 for iter_category in range(4):131 change_category = change_diff[iter_category]132 if iter_category == 0 and change_category:133 diff_strings.append("*++ Additional unexpected adds")134 elif iter_category == 1 and change_category:135 diff_strings.append("/++ Not present expected adds")136 elif iter_category == 2 and change_category:137 diff_strings.append("*-- Additional unexpected removes")138 elif iter_category == 3 and change_category:139 diff_strings.append("/-- Not present expected removes")140 for line_change in change_category:141 diff_strings.append(str(line_change).encode("string-escape"))142 return "\n".join(diff_strings)
storage.py
Source:storage.py
...4import os5# write file with content6def write_to_temp_file(content, ext):7 name = str(uuid4())8 path = get_temp_file_path(name=name)9 fpath = '{0}.{1}'.format(path, ext)10 with codecs.open(fpath, 'w', encoding='utf-8') as f:11 f.write(content)12 return name13# clear temp file14def clear_temp_file(name):15 if '..' in name or name in ['*', '']:16 raise Exception('Security exception')17 subprocess.call(['rm', '{0}*'.format(get_temp_file_path(name=name))])18def get_temp_file_path(dir='', name = None):19 _dir = os.path.join('/tmp/ace', dir)20 try:21 os.makedirs(_dir)22 except OSError:23 if not os.path.isdir(_dir):24 raise 25 return os.path.join(_dir, name) if name else _dir26def get_executable_path(name):27 return get_temp_file_path(dir='executable')28def get_simulation_problem_file_path(problem_id):29 dir = os.path.join('simulation', 'problems', problem_id)30 return get_temp_file_path(dir=dir, name='solution')31def get_analysis_problem_file_path(problem_id):32 dir = os.path.join('analysis', 'problems', problem_id)33 return get_temp_file_path(dir=dir, name='solution')34def get_simulation_problem_graphs_path(problem_id):35 dir = os.path.join('simulation', 'problems', problem_id, 'graphs')36 return get_temp_file_path(dir=dir)37def get_simulation_problem_submission_file_path(problem_id, submission_id):38 dir = os.path.join('simulation', 'problems', problem_id, 'submissions', submission_id)39 return get_temp_file_path(dir=dir, name='solution')40def get_analysis_problem_submission_file_path(problem_id, submission_id):41 dir = os.path.join('analysis', 'problems', problem_id, 'submissions', submission_id)42 return get_temp_file_path(dir=dir, name='solution')43def get_simulation_problem_submission_graphs_path(problem_id, submission_id):44 dir = os.path.join('simulation', 'problems', problem_id, 'submissions', submission_id, 'graphs')...
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!!