Best Python code snippet using avocado_python
diff_validator.py
Source:diff_validator.py
...17>>> import diff_validator18>>> change = diff_validator.Change()19>>> change.add_validated_files(["/etc/somerc"])20>>> change.append_expected_add("/etc/somerc", "this is a new line")21>>> change.append_expected_remove("/etc/somerc", "this line is removed")22>>> diff_validator.make_temp_file_copies(change.get_target_files())23After making changes through some in-test operation:24>>> changes = diff_validator.extract_changes(change.get_target_files())25>>> change_success = diff_validator.assert_change(changes, change.files_dict)26If test fails due to invalid change on the system:27>>> if not change_success:28>>> changes = diff_validator.assert_change_dict(changes, change.files_dict)29>>> raise DiffValidationError("Change is different than expected:\n%s" % diff_validator.create_diff_report(changes))30>>> else:31>>> logging.info("Change made successfully")32>>> diff_validator.del_temp_file_copies(change.get_target_files())33"""34import difflib35import os36import shutil37class DiffValidationError(Exception):38 pass39def get_temp_file_path(file_path):40 """41 Generates a temporary filename.42 :param str file_path: file path prefix43 :returns: appended file path44 :rtype: str45 """46 return file_path + '.tmp'47def make_temp_file_copies(file_paths):48 """49 Creates temporary copies of the provided files.50 :param file_paths: file paths to be copied51 :type file_paths: [str]52 """53 for file_path in file_paths:54 temp_file_path = get_temp_file_path(file_path)55 shutil.copyfile(file_path, temp_file_path)56def del_temp_file_copies(file_paths):57 """58 Deletes all the provided files.59 :param file_paths: deleted file paths (their temporary versions)60 :type file_paths: [str]61 """62 for file_path in file_paths:63 temp_file_path = get_temp_file_path(file_path)64 os.remove(temp_file_path)65def parse_unified_diff_output(lines):66 """67 Parses the unified diff output of two files.68 :param lines: diff lines69 :type lines: [str]70 :returns: pair of adds and removes, where each is a list of trimmed lines71 :rtype: ([str], [str])72 """73 adds = []74 removes = []75 for line in lines:76 # ignore filepaths in the output77 if (len(line) > 2 and (line[:3] == "+++" or78 line[:3] == "---")):79 continue80 # ignore line range information in the output81 elif len(line) > 1 and line[:2] == "@@":82 continue83 # gather adds84 elif len(line) > 0 and line[0] == "+":85 added_line = line[1:].lstrip().rstrip()86 if len(added_line) == 0:87 continue88 adds = adds + [added_line]89 # gather removes90 elif len(line) > 0 and line[0] == "-":91 removed_line = line[1:].lstrip().rstrip()92 if len(removed_line) == 0:93 continue94 removes = removes + [removed_line]95 return (adds, removes)96def extract_changes(file_paths, compared_file_paths=None):97 """98 Extracts diff information based on the new and temporarily saved old files.99 :param file_paths: original file paths (whose temporary versions will be retrieved)100 :type file_paths: [str]101 :param compared_file_paths: custom file paths to use instead of the temporary versions102 :type compared_file_paths: [str] or None103 :returns: file paths with corresponding diff information key-value pairs104 :rtype: {str, ([str], [str])}105 """106 changes = {}107 if compared_file_paths is None:108 compared_file_paths = []109 for i in range(len(file_paths)):110 temp_file_path = get_temp_file_path(file_paths[i])111 if len(compared_file_paths) > i:112 file1, file2 = compared_file_paths[i], file_paths[i]113 else:114 file1, file2 = temp_file_path, file_paths[i]115 with open(file1, encoding='utf-8') as f1:116 lines1 = f1.readlines()117 with open(file2, encoding='utf-8') as f2:118 lines2 = f2.readlines()119 lines = difflib.unified_diff(lines1, lines2,120 fromfile=file1, tofile=file2, n=0)121 changes[file_paths[i]] = parse_unified_diff_output(lines)122 return changes123def assert_change_dict(actual_result, expected_result):124 """125 Calculates unexpected line changes.126 :param actual_result: actual added and removed lines127 :type actual_result: {file_path, ([added_line, ...], [removed_line, ...])}128 :param expected_result: expected added and removed lines129 :type expected_result: {file_path, ([added_line, ...], [removed_line, ...])}130 :returns: detected differences as groups of lines with filepath keys and a tuple of131 (unexpected_adds, not_present_adds, unexpected_removes, not_present_removes)132 :rtype: {str, (str, str, str, str)}133 """134 change_diffs = {}135 for file_path, actual_changes in actual_result.items():136 expected_changes = expected_result[file_path]137 actual_adds = actual_changes[0]138 actual_removes = actual_changes[1]139 expected_adds = expected_changes[0]140 expected_removes = expected_changes[1]141 # Additional unexpected adds -- they should have been not added142 unexpected_adds = sorted(set(actual_adds) - set(expected_adds))143 # Not present expected adds -- they should have been added144 not_present_adds = sorted(set(expected_adds) - set(actual_adds))145 # Additional unexpected removes - they should have been not removed146 unexpected_removes = sorted(set(actual_removes) - set(expected_removes))147 # Not present expected removes - they should have been removed148 not_present_removes = sorted(set(expected_removes) -149 set(actual_removes))150 change_diffs[file_path] = (unexpected_adds, not_present_adds,151 unexpected_removes, not_present_removes)152 return change_diffs153def assert_change(actual_result, expected_result):154 """155 Condition wrapper of the upper method.156 :param actual_result: actual added and removed lines with filepath keys and a tuple of157 ([added_line, ...], [removed_line, ...])158 :type actual_result: {str, ([str], [str])}159 :param expected_result: expected added and removed lines of type as the actual result160 :type expected_result: {str, ([str], [str])}161 :returns: whether changes were detected162 :rtype: bool163 """164 change_diffs = assert_change_dict(actual_result, expected_result)165 for file_change in change_diffs.values():166 for line_change in file_change:167 if len(line_change) != 0:168 return False169 return True170def create_diff_report(change_diffs):171 """172 Pretty prints the output of the `change_diffs` variable.173 :param change_diffs: detected differences as groups of lines with filepath keys and a tuple of174 (unexpected_adds, not_present_adds, unexpected_removes, not_present_removes)175 :type: {str, (str, str, str, str)}176 :returns: print string of the line differences177 :rtype: str178 """179 diff_strings = []180 for file_path, change_diff in change_diffs.items():181 if not (change_diff[0] or change_diff[1] or182 change_diff[2] or change_diff[3]):183 continue184 diff_strings.append("--- %s" % get_temp_file_path(file_path))185 diff_strings.append("+++ %s" % file_path)186 for iter_category in range(4):187 change_category = change_diff[iter_category]188 if iter_category == 0 and change_category:189 diff_strings.append("*++ Additional unexpected adds")190 elif iter_category == 1 and change_category:191 diff_strings.append("/++ Not present expected adds")192 elif iter_category == 2 and change_category:193 diff_strings.append("*-- Additional unexpected removes")194 elif iter_category == 3 and change_category:195 diff_strings.append("/-- Not present expected removes")196 for line_change in change_category:197 diff_strings.append(str(line_change).encode('unicode_escape').decode())198 return "\n".join(diff_strings)199class Change():200 """Class for tracking and validating file changes"""201 def __init__(self):202 """Creates a change object."""203 self.files_dict = {}204 def get_target_files(self):205 """Get added files for change."""206 return list(self.files_dict.keys())207 def add_validated_files(self, filenames):208 """209 Add file to change object.210 :param filenames: files to validate211 :type filenames: [str]212 """213 for filename in filenames:214 self.files_dict[filename] = ([], [])215 def append_expected_add(self, filename, line):216 """217 Append expected added line to a file.218 :param str filename: file to append to219 :param str line: line to append to as an expected addition220 """221 try:222 self.files_dict[filename][0].append(line)223 except KeyError:224 self.files_dict[filename] = ([], [])225 self.files_dict[filename][0].append(line)226 def append_expected_remove(self, filename, line):227 """228 Append removed added line to a file.229 :param str filename: file to append to230 :param str line: line to append to as an expected removal231 """232 try:233 self.files_dict[filename][1].append(line)234 except KeyError:235 self.files_dict[filename] = ([], [])236 self.files_dict[filename][1].append(line)237 def get_all_adds(self):238 """Return a list of the added lines for all validated files."""239 all_adds = []240 for f in list(self.files_dict.keys()):...
test_diff_validator.py
Source:test_diff_validator.py
...28 f.write("this line is not removed\n")29 change = self.change30 change.add_validated_files(files)31 change.append_expected_add(files[0], "this is a new line")32 change.append_expected_remove(files[0], "this line is removed")33 change.append_expected_add(files[1], "this is a new line again")34 diff_validator.make_temp_file_copies(change.get_target_files())35 with open(files[0], "w", encoding="utf-8") as f:36 f.write("this is a new line")37 with open(files[1], "w", encoding="utf-8") as f:38 f.write("this line is not removed\nthis is a new line again\n")39 changes = diff_validator.extract_changes(change.get_target_files())40 change_success = diff_validator.assert_change(changes, change.files_dict)41 change_dict = diff_validator.assert_change_dict(changes, change.files_dict)42 self.assertTrue(43 change_success,44 f"The change must be valid:\n{diff_validator.create_diff_report(change_dict)}",45 )46 def test_change_wrong_no_change(self):47 files = self.files48 with open(files[0], "w", encoding="utf-8") as f:49 f.write("this line is removed\n")50 change = self.change51 change.add_validated_files(files)52 change.append_expected_add(files[0], "this is a new line")53 change.append_expected_remove(files[0], "this line is removed")54 diff_validator.make_temp_file_copies(change.get_target_files())55 changes = diff_validator.extract_changes(change.get_target_files())56 change_success = diff_validator.assert_change(changes, change.files_dict)57 change_dict = diff_validator.assert_change_dict(changes, change.files_dict)58 self.assertFalse(59 change_success,60 f"The change must not be valid:\n{diff_validator.create_diff_report(change_dict)}",61 )62 def test_change_wrong_add(self):63 files = self.files64 with open(files[0], "w", encoding="utf-8") as f:65 f.write("this line is removed\n")66 change = self.change67 change.add_validated_files(files)68 change.append_expected_add(files[0], "this is a new line")69 change.append_expected_remove(files[0], "this line is removed")70 diff_validator.make_temp_file_copies(change.get_target_files())71 with open(files[0], "w", encoding="utf-8") as f:72 f.write("this is a wrong new line\n")73 changes = diff_validator.extract_changes(change.get_target_files())74 change_success = diff_validator.assert_change(changes, change.files_dict)75 change_dict = diff_validator.assert_change_dict(changes, change.files_dict)76 self.assertFalse(77 change_success,78 f"The change must not be valid:\n{diff_validator.create_diff_report(change_dict)}",79 )80 def test_change_unexpected_remove(self):81 files = self.files82 with open(files[0], "w", encoding="utf-8") as f:83 f.write("this line is removed\n")84 change = self.change85 change.add_validated_files(files)86 change.append_expected_add(files[0], "this is a new line")87 diff_validator.make_temp_file_copies(change.get_target_files())88 with open(files[0], "w", encoding="utf-8") as f:89 f.write("this is a new line\n")90 changes = diff_validator.extract_changes(change.get_target_files())91 change_success = diff_validator.assert_change(changes, change.files_dict)92 change_dict = diff_validator.assert_change_dict(changes, change.files_dict)93 self.assertFalse(94 change_success,95 f"The change must not be valid:\n{diff_validator.create_diff_report(change_dict)}",96 )97 def test_change_unexpected_add(self):98 files = self.files99 with open(files[0], "w", encoding="utf-8") as f:100 f.write("this line is removed\n")101 change = self.change102 change.add_validated_files(files)103 change.append_expected_remove(files[0], "this line is removed")104 diff_validator.make_temp_file_copies(change.get_target_files())105 with open(files[0], "w", encoding="utf-8") as f:106 f.write("this is an unexpected new line\n")107 changes = diff_validator.extract_changes(change.get_target_files())108 change_success = diff_validator.assert_change(changes, change.files_dict)109 change_dict = diff_validator.assert_change_dict(changes, change.files_dict)110 self.assertFalse(111 change_success,112 f"The change must not be valid:\n{diff_validator.create_diff_report(change_dict)}",113 )114if __name__ == "__main__":...
test_utils_diff_validator.py
Source:test_utils_diff_validator.py
...26 f.write("this line is not removed\n")27 change = self.change28 change.add_validated_files(files)29 change.append_expected_add(files[0], "this is a new line")30 change.append_expected_remove(files[0], "this line is removed")31 change.append_expected_add(files[1], "this is a new line again")32 diff_validator.make_temp_file_copies(change.get_target_files())33 with open(files[0], "w") as f:34 f.write("this is a new line")35 with open(files[1], "w") as f:36 f.write("this line is not removed\nthis is a new line again\n")37 changes = diff_validator.extract_changes(change.get_target_files())38 change_success = diff_validator.assert_change(changes, change.files_dict)39 change_dict = diff_validator.assert_change_dict(changes, change.files_dict)40 self.assertTrue(change_success, "The change must be valid:\n%s" % diff_validator.create_diff_report(change_dict))41 def test_change_wrong_no_change(self):42 files = self.files43 with open(files[0], "w") as f:44 f.write("this line is removed\n")45 change = self.change46 change.add_validated_files(files)47 change.append_expected_add(files[0], "this is a new line")48 change.append_expected_remove(files[0], "this line is removed")49 diff_validator.make_temp_file_copies(change.get_target_files())50 changes = diff_validator.extract_changes(change.get_target_files())51 change_success = diff_validator.assert_change(changes, change.files_dict)52 change_dict = diff_validator.assert_change_dict(changes, change.files_dict)53 self.assertFalse(change_success, "The change must not be valid:\n%s" % diff_validator.create_diff_report(change_dict))54 def test_change_wrong_add(self):55 files = self.files56 with open(files[0], "w") as f:57 f.write("this line is removed\n")58 change = self.change59 change.add_validated_files(files)60 change.append_expected_add(files[0], "this is a new line")61 change.append_expected_remove(files[0], "this line is removed")62 diff_validator.make_temp_file_copies(change.get_target_files())63 with open(files[0], "w") as f:64 f.write("this is a wrong new line\n")65 changes = diff_validator.extract_changes(change.get_target_files())66 change_success = diff_validator.assert_change(changes, change.files_dict)67 change_dict = diff_validator.assert_change_dict(changes, change.files_dict)68 self.assertFalse(change_success, "The change must not be valid:\n%s" % diff_validator.create_diff_report(change_dict))69 def test_change_unexpected_remove(self):70 files = self.files71 with open(files[0], "w") as f:72 f.write("this line is removed\n")73 change = self.change74 change.add_validated_files(files)75 change.append_expected_add(files[0], "this is a new line")76 diff_validator.make_temp_file_copies(change.get_target_files())77 with open(files[0], "w") as f:78 f.write("this is a new line\n")79 changes = diff_validator.extract_changes(change.get_target_files())80 change_success = diff_validator.assert_change(changes, change.files_dict)81 change_dict = diff_validator.assert_change_dict(changes, change.files_dict)82 self.assertFalse(change_success, "The change must not be valid:\n%s" % diff_validator.create_diff_report(change_dict))83 def test_change_unexpected_add(self):84 files = self.files85 with open(files[0], "w") as f:86 f.write("this line is removed\n")87 change = self.change88 change.add_validated_files(files)89 change.append_expected_remove(files[0], "this line is removed")90 diff_validator.make_temp_file_copies(change.get_target_files())91 with open(files[0], "w") as f:92 f.write("this is an unexpected new line\n")93 changes = diff_validator.extract_changes(change.get_target_files())94 change_success = diff_validator.assert_change(changes, change.files_dict)95 change_dict = diff_validator.assert_change_dict(changes, change.files_dict)96 self.assertFalse(change_success, "The change must not be valid:\n%s" % diff_validator.create_diff_report(change_dict))97if __name__ == '__main__':...
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!!