Best Python code snippet using avocado_python
artifact_manager.py
Source:artifact_manager.py
1"""2Copyright (c) Contributors to the Open 3D Engine Project.3For complete copyright and license terms please see the LICENSE at the root of this distribution.4SPDX-License-Identifier: Apache-2.0 OR MIT5Workspace Manager: Provides an API for managing lumberyard installations and file manipulation6"""7import logging8import os9import shutil10import six11import stat12import tempfile13import re14import ly_test_tools.environment.file_system as file_system15logger = logging.getLogger(__name__)16class ArtifactManager(object):17 def __init__(self, root):18 self.artifact_path = root # i.e.: ~/dev/TestResults/2019-10-15T13_38_42_855000/19 self.dest_path = None20 self._set_dest_path() # Sets the self.dest_path attribute as the main artifact save path for test files.21 def _get_collision_handled_filename(self, file_path, amount=1):22 # type: (str, int) -> str23 """24 Handles filename collision by appending integers, checking if the file exists, then incrementing if so. Will25 increase up to the amount parameter before stopping.26 :param file_path: The file path as a string to check for name collisions27 :param amount: amount of renames possible for the string if file_path collision occurs by appending integers to28 the name. If the amount is reached, the save will override the file instead.29 :return: The new file_path as a string30 """31 # Name collision handling not needed for 1 name32 if amount == 1:33 return file_path34 # extension will be an empty string if it doesn't exist35 file_without_ext, extension = os.path.splitext(file_path)36 for i in range(1, amount): # Start at "_1" instead of "_0"37 updated_path = f"{file_without_ext}_{i}{extension}"38 if not os.path.exists(updated_path):39 return updated_path40 logger.info(f"Maximum number of attempts: {amount} met when trying to handle name collision for file: "41 f"{file_path}. Ending on {updated_path} which will override the existing file.")42 return updated_path43 def _set_dest_path(self, test_name=None, amount=1):44 """45 Sets self.dest_path if not set, and returns the value currently set in self.dest_path. Also creates the46 directory if it already doesn't exist.47 :param test_name: If set, will update self.dest_path to include the test_name value passed.48 :param amount: The amount of folders to create matching self.dest_path and adding an index value to each.49 :return: None, but sets the self.dest_path attribute when called.50 """51 if test_name:52 self.dest_path = os.path.join(self.dest_path, file_system.sanitize_file_name(test_name))53 elif not self.dest_path:54 self.dest_path = self.artifact_path55 # Create unique artifact folder56 if not os.path.exists(self.dest_path):57 self.dest_path = self._get_collision_handled_filename(self.dest_path, amount)58 try:59 logger.debug(f'Attempting to create new artifact path: "{self.dest_path}"')60 if not os.path.exists(self.dest_path):61 os.makedirs(self.dest_path)62 logger.info(f'Created new artifact path: "{self.dest_path}"')63 return self.dest_path64 except (IOError, OSError, WindowsError) as err:65 problem = WindowsError(f'Failed to create new artifact path: "{self.dest_path}"')66 six.raise_from(problem, err)67 def set_test_name(self, test_name=None, amount=1):68 """69 Set the test name used to log the artifacts, if set, all artifacts are saved to a subdir named after this test.70 This value will get appended to the main path in the self.dest_path attribute.71 :param test_name: Name of the test, format of "module_class_method",72 i.e.: "test_module_TestClass_test_BasicTestMethod_ValidInputTest_ReturnsTrue_1"73 :param amount: int representing the amount of folders to create for test_name74 :return: None but updates the self.dest_path attribute with the test name in it.75 """76 self._set_dest_path(test_name=test_name, amount=amount)77 def generate_folder_name(self, test_module, test_class, test_method):78 """79 Takes a test module, class, & method and generates a folder name string with an added80 count value to make the name unique for test methods that run multiple times.81 Returns the newly generated folder name string.82 :param test_module: string for the name of the current test module83 :param test_class: string for the name of the current test class84 :param test_method: string for the name of the current test method85 :return: string for naming a folder that represents the current test, with a maximum length86 of 60 trimmed down to match this requirement.87 """88 folder_name = file_system.reduce_file_name_length(89 file_name="{}_{}_{}".format(test_module, test_class, test_method),90 max_length=60)91 return folder_name92 def save_artifact(self, artifact_path, artifact_name=None, amount=1):93 """94 Store an artifact to be logged. Will ensure the new artifact is writable to prevent directory from being95 locked later.96 :param artifact_path: string representing the full path to the artifact folder.97 :param artifact_name: string representing a new artifact name for log if necessary, max length: 25 characters.98 :param amount: amount of renames possible for the saved artifact if file name collision occurs by appending99 integers to the name. If the amount is reached, the save will override the file instead.100 """101 if artifact_name:102 artifact_name = file_system.reduce_file_name_length(file_name=artifact_name, max_length=25)103 dest_path = os.path.join(self.dest_path,104 artifact_name if artifact_name is not None else os.path.basename(artifact_path))105 if os.path.exists(dest_path):106 dest_path = self._get_collision_handled_filename(dest_path, amount)107 logger.debug("Copying artifact from '{}' to '{}'".format(artifact_path, dest_path))108 if os.path.isdir(artifact_path):109 shutil.copytree(artifact_path, dest_path)110 else:111 shutil.copy(artifact_path, dest_path)112 os.chmod(dest_path, stat.S_IWRITE | stat.S_IREAD | stat.S_IEXEC)113 def generate_artifact_file_name(self, artifact_name):114 """115 Returns a string for generating a new artifact file inside of the artifact folder.116 :param artifact_name: string representing the name for the artifact file (i.e. "ToolsInfo.log")117 :return: string for the full path to the file inside the artifact path even if not valid, i.e.:118 ~/dev/TestResults/2019-10-14T11_36_12_234000/pytest_results/test_module_TestClass_Method_1/ToolsInfo.log119 """120 if not artifact_name:121 raise ValueError('artifact_name is a required parameter for generate_artifact_file_name()')122 file_path = os.path.join(self.dest_path,123 artifact_name)124 return file_path125 def gather_artifacts(self, destination, format='zip'):126 """127 Gather collected artifacts to the specified destination as an archive file (zip by default).128 Destination should not contain file extension, the second parameter automatically determines the best extension129 to use.130 :param destination: where to write the archive file, do not add extension131 :param format: archive format, default is 'zip', possible values: tar, gztar and bztar.132 :return: full path to the generated archive or raises a WindowsError if shutil.mark_archive() fails.133 """134 try:135 return shutil.make_archive(destination, format, self.dest_path)136 except WindowsError:137 logger.exception(138 'Windows failed to find the target artifact path: "{}" '139 'which may indicate test setup failed.'.format(self.dest_path))140class NullArtifactManager(ArtifactManager):141 """142 An ArtifactManager that ignores all calls, used when logging is not configured.143 """144 def __init__(self):145 # The null ArtifactManager redirects all calls to a temp dir146 super(NullArtifactManager, self).__init__(tempfile.mkdtemp())147 def _get_collision_handled_filename(self, artifact_path=None, amount=None):148 raise NotImplementedError("Attempt was made to create artifact save paths through NullArtifactManager.")149 def save_artifact(self, artifact, artifact_name=None, amount=None):150 return None151 def gather_artifacts(self, destination, format='zip'):...
python_unittest.py
Source:python_unittest.py
...54 return None55 module_path = uri.rsplit(":", 1)[0]56 return os.path.dirname(module_path)57 @property58 def module_class_method(self):59 """Return a dotted name with module + class + method.60 Important to note here that module is only the module file without the61 full path.62 """63 unittest = self.unittest64 if not unittest:65 return None66 return ".".join(unittest)67 @classmethod68 def _run_unittest(cls, module_path, module_class_method, queue):69 sys.path.insert(0, module_path)70 stream = io.StringIO()71 try:72 loader = TestLoader()...
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!!