How to use _get_checksum_dict method in autotest

Best Python code snippet using autotest_python

base_packages.py

Source:base_packages.py Github

copy

Full Screen

...543 Return the complete path of the checksum file (assumed to be stored544 in self.pkgmgr_dir545 '''546 return os.path.join(self.pkgmgr_dir, CHECKSUM_FILE)547 def _get_checksum_dict(self):548 '''549 Fetch the checksum file if not already fetched. If the checksum file550 cannot be fetched from the repos then a new file is created with551 the current package's (specified in pkg_path) checksum value in it.552 Populate the local checksum dictionary with the values read from553 the checksum file.554 The checksum file is assumed to be present in self.pkgmgr_dir555 '''556 checksum_path = self._get_checksum_file_path()557 if not self._checksum_dict:558 # Fetch the checksum file559 try:560 try:561 self._run_command("ls %s" % checksum_path)562 except (error.CmdError, error.AutoservRunError):563 # The packages checksum file does not exist locally.564 # See if it is present in the repositories.565 self.fetch_pkg(CHECKSUM_FILE, checksum_path)566 except error.PackageFetchError:567 # This should not happen whilst fetching a package..if a568 # package is present in the repository, the corresponding569 # checksum file should also be automatically present. This570 # case happens only when a package571 # is being uploaded and if it is the first package to be572 # uploaded to the repos (hence no checksum file created yet)573 # Return an empty dictionary in that case574 return {}575 # Read the checksum file into memory576 checksum_file_contents = self._run_command('cat '577 + checksum_path).stdout578 # Return {} if we have an empty checksum file present579 if not checksum_file_contents.strip():580 return {}581 # Parse the checksum file contents into self._checksum_dict582 for line in checksum_file_contents.splitlines():583 checksum, package_name = line.split(None, 1)584 self._checksum_dict[package_name] = checksum585 return self._checksum_dict586 def _save_checksum_dict(self, checksum_dict):587 '''588 Save the checksum dictionary onto the checksum file. Update the589 local _checksum_dict variable with this new set of values.590 checksum_dict : New checksum dictionary591 checksum_dir : The directory in which to store the checksum file to.592 '''593 checksum_path = self._get_checksum_file_path()594 self._checksum_dict = checksum_dict.copy()595 checksum_contents = '\n'.join(checksum + ' ' + pkg_name596 for pkg_name, checksum in597 checksum_dict.iteritems())598 # Write the checksum file back to disk599 self._run_command('echo "%s" > %s' % (checksum_contents,600 checksum_path),601 _run_command_dargs={'verbose': False})602 def compute_checksum(self, pkg_path):603 '''604 Compute the MD5 checksum for the package file and return it.605 pkg_path : The complete path for the package file606 '''607 md5sum_output = self._run_command("md5sum %s " % pkg_path).stdout608 return md5sum_output.split()[0]609 def update_checksum(self, pkg_path):610 '''611 Update the checksum of the package in the packages' checksum612 file. This method is called whenever a package is fetched just613 to be sure that the checksums in the local file are the latest.614 pkg_path : The complete path to the package file.615 '''616 # Compute the new checksum617 new_checksum = self.compute_checksum(pkg_path)618 checksum_dict = self._get_checksum_dict()619 checksum_dict[os.path.basename(pkg_path)] = new_checksum620 self._save_checksum_dict(checksum_dict)621 def remove_checksum(self, pkg_name):622 '''623 Remove the checksum of the package from the packages checksum file.624 This method is called whenever a package is removed from the625 repositories in order clean its corresponding checksum.626 pkg_name : The name of the package to be removed627 '''628 checksum_dict = self._get_checksum_dict()629 if pkg_name in checksum_dict:630 del checksum_dict[pkg_name]631 self._save_checksum_dict(checksum_dict)632 def compare_checksum(self, pkg_path):633 '''634 Calculate the checksum of the file specified in pkg_path and635 compare it with the checksum in the checksum file636 Return True if both match else return False.637 pkg_path : The full path to the package file for which the638 checksum is being compared639 '''640 checksum_dict = self._get_checksum_dict()641 package_name = os.path.basename(pkg_path)642 if not checksum_dict or package_name not in checksum_dict:643 return False644 repository_checksum = checksum_dict[package_name]645 local_checksum = self.compute_checksum(pkg_path)646 return (local_checksum == repository_checksum)647 def tar_package(self, pkg_name, src_dir, dest_dir, exclude_string=None):648 '''649 Create a tar.bz2 file with the name 'pkg_name' say test-blah.tar.bz2.650 Excludes the directories specified in exclude_string while tarring651 the source. Returns the tarball path.652 '''653 tarball_path = os.path.join(dest_dir, pkg_name)654 temp_path = tarball_path + '.tmp'...

Full Screen

Full Screen

tamper-check

Source:tamper-check Github

copy

Full Screen

...23 if user_inp in ('y', 'yes'):24 return True25 elif user_inp in ('n', 'no'):26 return False27def _get_checksum_dict(checksum_file: Path) -> dict[Path, str]:28 """Read the JSON checksum file and return it as python dictionary object."""29 try:30 with open(checksum_file, 'r') as f:31 checksums = json.load(f)32 except FileNotFoundError:33 print(34 f'{colorama.Fore.YELLOW}Checksum file not found: {colorama.Fore.RESET}'35 f"'{colorama.Fore.BLUE}{checksum_file}{colorama.Fore.RESET}'{colorama.Fore.YELLOW} "36 'Creating new empty checksum file...'37 )38 checksum_file.parent.mkdir(parents=True, exist_ok=True)39 checksums = {}40 with open(checksum_file, 'w') as f:41 json.dump(checksums, f, indent=4)42 return checksums43 except PermissionError:44 print(45 f'{colorama.Fore.RED}PermissionError: {colorama.Fore.RESET}'46 'to run tamper-check you must have read access to checksum file: '47 f"'{colorama.Fore.BLUE}{checksum_file}{colorama.Fore.RESET}' (forgot sudo?)"48 )49 exit(2)50 except json.decoder.JSONDecodeError as e:51 print(52 f'{colorama.Fore.RED}Checksum file is corrupted, unable to decode JSON. '53 f"{colorama.Fore.RESET}('{colorama.Fore.BLUE}{checksum_file}{colorama.Fore.RESET}').\n"54 f'Error text: {e}'55 )56 exit(3)57 else:58 dct = {}59 for file_str, checksum in checksums.items():60 dct[Path(file_str)] = checksum61 return dct62def _get_checksum(file: Path) -> str:63 """Obtain a checksum of given file"""64 proc = subprocess.run(['sha256sum', file], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)65 proc_stdout = proc.stdout.decode('utf-8')66 if "No such file or directory" in proc_stdout:67 raise FileNotFoundError(f"'{file}' not found, can't produce sha256 checksum")68 elif "Permission denied" in proc_stdout:69 raise PermissionError(f"Unable to read file '{file}'")70 elif "Is a directory" in proc_stdout:71 raise RuntimeError(f"{file} is a directory, can't produce sha256sum")72 return proc_stdout.replace(f' {file}\n', '')73def _update_checksum(file_path: Path, checksum: str, checksum_file: Path, new_entry: bool = False) -> None:74 """Update existing checksums or add new file entries in checksum_file"""75 checksums = _get_checksum_dict(checksum_file)76 if new_entry and file_path in checksums:77 print(78 f"{colorama.Fore.RED}Path {colorama.Fore.RESET}"79 f"'{colorama.Fore.BLUE}{file_path}{colorama.Fore.RESET}' {colorama.Fore.RED}"80 "is already in the checksum file perhaps you wanted `--update`?"81 )82 raise SystemExit(3)83 checksums[file_path] = checksum84 writeable_checksums = {str(file_path): file_checksum for file_path, file_checksum in checksums.items()}85 try:86 with open(checksum_file, 'w') as f:87 json.dump(writeable_checksums, f, indent=4)88 except PermissionError:89 print(90 f'{colorama.Fore.RED}PermissionError: {colorama.Fore.RESET}'91 'To add a new rule, you must have write access to: '92 f"'{colorama.Fore.BLUE}{checksum_file}{colorama.Fore.RESET}' (forgot sudo?)"93 )94 raise SystemExit(2)95def update(file_path: Path, checksum_file: Path, text: str, no_confirm: bool = False) -> bool:96 """Ask user if a file should be updated, or update automatically if no_confirm is True"""97 new_checksum = _get_checksum(file_path)98 if no_confirm:99 print(text + ' checksum auto-updating')100 elif not _yes_no(text + ' update checksum?'):101 print(f'{colorama.Fore.RED} -> Staying mismatched')102 return False103 _update_checksum(file_path, new_checksum, checksum_file)104 print(f'{colorama.Fore.GREEN} -> Updated')105 return True106def run_check(checksum_file: Path, verbose: bool) -> list[Path]:107 """108 Go through all files listed in checksum_file and make sure that the checksums are matching.109 Return all entries which didn't match.110 """111 checksums = _get_checksum_dict(checksum_file)112 not_matched = []113 for file, stored_checksum in checksums.items():114 line = f"Checksum of '{colorama.Fore.BLUE}{file}{colorama.Fore.RESET}': "115 try:116 real_sha256_sum = _get_checksum(file)117 except PermissionError as exc:118 print(line + f'{colorama.Fore.YELLOW}SKIPPED [PermissionError - no read perms]')119 if verbose:120 print(f' -> Error text: {colorama.Fore.CYAN}{exc}')121 continue122 except FileNotFoundError as exc:123 print(line + f'{colorama.Fore.YELLOW}FAILED [FileNotFound - fix checksum file]')124 if verbose:125 print(f' -> Error text: {colorama.Fore.CYAN}{exc}')...

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 autotest 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