How to use _process_files method in autotest

Best Python code snippet using autotest_python

modified.py

Source:modified.py Github

copy

Full Screen

1__author__ = 'Scott Maxwell'2__version__ = "1.04"3__project_url__ = "https://github.com/codecobblers/modified"4# Copyright (C) 2013 by Scott Maxwell5#6# Permission is hereby granted, free of charge, to any person obtaining a copy7# of this software and associated documentation files (the "Software"), to deal8# in the Software without restriction, including without limitation the rights9# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell10# copies of the Software, and to permit persons to whom the Software is11# furnished to do so, subject to the following conditions:12#13# The above copyright notice and this permission notice shall be included in14# all copies or substantial portions of the Software.15#16# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR17# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE19# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER20# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22# THE SOFTWARE.23"""24modified tracks the files of the currently running application and facilitates25restart if any files have changed. By default it will track all Python files,26including all modules loaded by the app. If there are additional files you27need to track such as config files, templates, etc., you can add those using28the track function.29The simplest usage is to simply run the hup_hook. By default, this will build30a dict of all currently loaded code files with their timestamps and register31a handler for `signal.SIGHUP`. When the application receives `signal.SIGHUP`,32the hook will check to see if any of the files have been modified, and issue33`signal.SIGTERM`, if so.34@note: If a file ends in `.pyc`, `modified` will attempt to retrieve35the timestamp from the `.py` file instead.36"""37import sys38import os39import signal40_process_files = {}41_scanned = False42if sys.version_info[0] == 3 and sys.version_info[1] < 3:43 from collections import Callable44 #noinspection PyShadowingBuiltins45 def callable(o):46 return isinstance(o, Callable)47def _get_filename_and_modified(filename):48 path = filename49 while path:50 try:51 if path.endswith('.pyc'):52 try:53 return path[:-1], os.stat(path[:-1]).st_mtime54 except Exception:55 pass56 return path, os.stat(path).st_mtime57 except Exception:58 path = os.path.dirname(path)59 if os.path.isdir(path):60 break61 return None, 062def _get_modified(filename):63 try:64 return os.stat(filename).st_mtime65 except Exception:66 return 067def module_files(module, dependencies_dict=None):68 """69 Scan a module and its entire dependency tree to create a dict of all files70 and their modified time.71 @param module: A <module> object72 @param dependencies_dict: Pass an existing dict to add only unscanned73 files or None to create a new file dict74 @return: A dict containing filenames as keys with their modified time75 as value76 """77 if dependencies_dict is None:78 dependencies_dict = dict()79 if hasattr(module, '__file__'):80 filename = module.__file__81 if filename not in dependencies_dict:82 realname, modified_time = _get_filename_and_modified(filename)83 if realname and realname not in dependencies_dict:84 dependencies_dict[realname] = modified_time85 for name in dir(module):86 try:87 item = getattr(module, name)88 if hasattr(item, '__file__'):89 module_files(item, dependencies_dict)90 elif hasattr(item, '__module__'):91 item = sys.modules[getattr(item, '__module__')]92 if hasattr(item, '__file__'):93 module_files(item, dependencies_dict)94 except (AttributeError, KeyError):95 pass96 return dependencies_dict97def files():98 """99 Scan all modules in the currently running app to create a dict of all100 files and their modified time.101 @note The scan only occurs the first time this function is called.102 Subsequent calls simply return the global dict.103 @return: A dict containing filenames as keys with their modified time104 as value105 """106 if not _scanned:107 if not module_files(sys.modules['__main__'], _process_files):108 for module in sys.modules.values():109 if hasattr(module, '__file__'):110 filename = module.__file__111 if filename not in _process_files:112 realname, modified_time = _get_filename_and_modified(filename)113 if realname and realname not in _process_files:114 _process_files[realname] = modified_time115 return _process_files116def modified():117 """118 Get the modified list.119 @return: A list of all tracked files that have been modified since the120 initial scan.121 """122 return [filename for filename, modified_timestamp in _process_files.items() if modified_timestamp != _get_modified(filename)]123def track(*args):124 """125 Track additional files. It is often useful to use glob.glob here.126 For instance:127 track('config.ini', glob.glob('templates/*.pt'), glob.glob('db/*.db'))128 @param args: A list where each element is either a filename or an129 iterable of filenames130 """131 for arg in args:132 if isinstance(arg, str):133 arg = [arg]134 for filename in arg:135 realname, modified_time = _get_filename_and_modified(filename)136 if realname and realname not in _process_files:137 _process_files[realname] = modified_time138def hup_hook(signal_or_callable=signal.SIGTERM, verbose=False):139 """140 Register a signal handler for `signal.SIGHUP` that checks for modified141 files and only acts if at least one modified file is found.142 @type signal_or_callable: str, int or callable143 @param signal_or_callable: You can pass either a signal or a callable.144 The signal can be specified by name or number. If specifying by name,145 the 'SIG' portion is optional. For example, valid values for SIGINT146 include 'INT', 'SIGINT' and `signal.SIGINT`.147 Alternatively, you can pass a callable that will be called with the list148 of changed files. So the call signature should be `func(list)`. The return149 value of the callable is ignored.150 @type verbose: bool or callable151 @param verbose: Defaults to False. True indicates that a message should be152 printed. You can also pass a callable such as log.info.153 """154 #noinspection PyUnusedLocal155 def handle_hup(signum, frame):156 changed = modified()157 if changed:158 if callable(signal_or_callable):159 func = signal_or_callable160 args = (changed,)161 op = 'Calling'162 try:163 name = signal_or_callable.__name__164 except Exception:165 name = str(signal_or_callable)166 else:167 if isinstance(signal_or_callable, int):168 name = str(signal_or_callable)169 signum = signal_or_callable170 if verbose:171 for item in dir(signal):172 if item.startswith('SIG') and getattr(signal, item) == signal_or_callable:173 name = item174 break175 else:176 name = signal_or_callable if signal_or_callable.startswith('SIG') else 'SIG' + signal_or_callable177 signum = getattr(signal, name)178 func = os.kill179 args = (os.getpid(), signum)180 op = 'Sending'181 if verbose:182 more = ' and {0} other files'.format(len(changed)) if len(changed) > 1 else ''183 message = '{0} {1} because {2}{3} changed'.format(op, name, changed[0], more)184 if callable(verbose):185 #noinspection PyCallingNonCallable186 verbose(message)187 else:188 print(message)189 func(*args)190 files()191 signal.signal(signal.SIGHUP, handle_hup)...

Full Screen

Full Screen

result.py

Source:result.py Github

copy

Full Screen

...59 self._frame_files = None60 self._score_files = None61 self.score_results = []62 self._is_processed = False63 def _process_files(self) -> None:64 # this whole processing assumes 1v1 bot vs bot games65 if self._is_processed:66 return67 self._is_processed = True68 if self.is_realtime_outed:69 return70 num_players = len(self.players)71 if len(self.score_files) != num_players:72 logger.warning(f"Not all score files have been recorded for game '{self.game_name}'")73 logger.warning(f"Expected {num_players} score files, got {len(self.score_files)}")74 logger.warning("Assuming a crash happened.")75 self._is_crashed = True76 return77 scores = {score_file: ScoreResult.load_score(score_file)78 for score_file in sorted(self.score_files)}79 if any(score.is_crashed for score in scores.values()):80 logger.warning(f"Some of the players crashed in game '{self.game_name}'")81 self._is_crashed = True82 return83 if not any(score.is_winner for score in scores.values()):84 logger.warning(f"No winner found in game '{self.game_name}'")85 logger.warning("Assuming a crash happened.")86 self._is_crashed = True87 return88 if sum(int(score.is_winner) for score in scores.values()) > 1:89 logger.warning(f"There are multiple winners of a game '{self.game_name}'")90 logger.warning("This can indicates possible game result corruption!")91 logger.warning("Assuming a crash happened.")92 self._is_crashed = True93 return94 winner_score_file = [file for file, score in scores.items() if score.is_winner][0]95 nth_player = int(winner_score_file.replace("/scores.json", "").replace("\\scores.json", "").split("_")[-1])96 self._nth_winner_player = nth_player97 self._nth_loser_player = 1 - nth_player98 self._winner_player = self.players[self._nth_winner_player]99 self._loser_player = self.players[self._nth_loser_player]100 self._is_crashed = False101 # todo: implement, maybe according to SSCAIT rules?102 self._is_gametime_outed = False103 self.score_results = scores104 @property105 def replay_files(self) -> List[str]:106 if self._replay_files is None:107 self._replay_files = find_replays(self.game_dir, self.game_name)108 return self._replay_files109 @property110 def log_files(self) -> List[str]:111 if self._log_files is None:112 self._log_files = find_logs(self.game_dir, self.game_name)113 return self._log_files114 @property115 def frame_files(self) -> List[str]:116 if self._frame_files is None:117 self._frame_files = find_frames(self.game_dir, self.game_name)118 return self._frame_files119 @property120 def score_files(self) -> List[str]:121 if self._score_files is None:122 self._score_files = find_scores(self.game_dir, self.game_name)123 return self._score_files124 # Bunch of getters125 @property126 def is_valid(self) -> bool:127 self._process_files()128 return not self.is_crashed and \129 not self.is_gametime_outed and \130 not self.is_realtime_outed131 @property132 def is_crashed(self) -> bool:133 self._process_files()134 return self._is_crashed135 @property136 def is_gametime_outed(self) -> bool:137 self._process_files()138 return self._is_gametime_outed139 @property140 def winner_player(self) -> Optional[Player]:141 self._process_files()142 return self._winner_player143 @property144 def nth_winner_player(self) -> Optional[int]:145 self._process_files()146 return self._nth_winner_player147 @property148 def loser_player(self) -> Optional[Player]:149 self._process_files()150 return self._loser_player151 @property152 def nth_loser_player(self) -> Optional[int]:153 self._process_files()...

Full Screen

Full Screen

thumbs-nautilus.py

Source:thumbs-nautilus.py Github

copy

Full Screen

...15from gi import require_version16require_version('Nautilus', '3.0')17from gi.repository import Nautilus, GObject, Gio, GLib18class DeleteThumbnailsAction(GObject.GObject, Nautilus.MenuProvider):19 def _process_files(self, files):20 paths = []21 for file in files:22 path = file.get_location().get_path()23 if path and path not in paths:24 paths.append(path)25 return paths26 def _make_menu(self, name, paths):27 menu = Nautilus.MenuItem(name=name, label='Delete thumbnails', icon='edit-delete-symbolic')28 menu.connect('activate', self._run_thumbs, paths)29 return menu30 def get_file_items(self, window, files):31 paths = self._process_files(files)32 if paths:33 return [self._make_menu(name='ThumbsNautilus::delete_thumbs_for_files', paths=paths)]34 else:35 return []36 def get_background_items(self, window, file):37 paths = self._process_files([file])38 if paths:39 return [self._make_menu(name='ThumbsmNautilus::delete_thumbs_for_folder', paths=paths)]40 else:41 return []42 def _run_thumbs(self, _menu, paths):43 cmd = ['thumbs', 'delete', '-r', '-f'] + paths...

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