text
stringlengths
81
112k
Bind or connect the nanomsg socket to some address def initialize(self, timeouts): """ Bind or connect the nanomsg socket to some address """ # Bind or connect to address if self.bind is True: self.socket.bind(self.address) else: self.socket.connect(self.address...
Set socket timeouts for send and receive respectively def _set_timeouts(self, timeouts): """ Set socket timeouts for send and receive respectively """ (send_timeout, recv_timeout) = (None, None) try: (send_timeout, recv_timeout) = timeouts except TypeError: rai...
Encode and sign (optional) the send through socket def send(self, payload): """ Encode and sign (optional) the send through socket """ payload = self.encode(payload) payload = self.sign(payload) self.socket.send(payload)
Receive from socket, authenticate and decode payload def receive(self, decode=True): """ Receive from socket, authenticate and decode payload """ payload = self.socket.recv() payload = self.verify(payload) if decode: payload = self.decode(payload) return payload
Sign payload using the supplied authenticator def sign(self, payload): """ Sign payload using the supplied authenticator """ if self.authenticator: return self.authenticator.signed(payload) return payload
Verify payload authenticity via the supplied authenticator def verify(self, payload): """ Verify payload authenticity via the supplied authenticator """ if not self.authenticator: return payload try: self.authenticator.auth(payload) return self.authenticator....
Decode payload def decode(self, payload): """ Decode payload """ try: return self.encoder.decode(payload) except Exception as exception: raise DecodeError(str(exception))
Encode payload def encode(self, payload): """ Encode payload """ try: return self.encoder.encode(payload) except Exception as exception: raise EncodeError(str(exception))
Start and listen for calls def start(self): """ Start and listen for calls """ if threading.current_thread().name == 'MainThread': signal.signal(signal.SIGINT, self.stop) logging.info('Started on {}'.format(self.address)) while True: self.process()
Shutdown process (this method is also a signal handler) def stop(self, dummy_signum=None, dummy_frame=None): """ Shutdown process (this method is also a signal handler) """ logging.info('Shutting down ...') self.socket.close() sys.exit(0)
summarize the report data @param list_all: a list which save the report data @param kwargs: such as show_all: True/False report show all status cases proj_name: project name home_page: home page url def get_summary(list_all=[], **kw...
add report data to a list @param list_all: a list which save the report data @param module_name: test set name or test module name @param kwargs: such as case_name: testcase name status: test result, Pass or Fail resp_teste...
Fetch the function registered for a certain subscription def parse(self, subscription): """ Fetch the function registered for a certain subscription """ for name in self.methods: tag = bytes(name.encode('utf-8')) if subscription.startswith(tag): fun = self.metho...
Subscribe to something and register a function def subscribe(self, tag, fun, description=None): """ Subscribe to something and register a function """ self.methods[tag] = fun self.descriptions[tag] = description self.socket.set_string_option(nanomsg.SUB, nanomsg.SUB_SUBSCRIBE, tag)
Receive a subscription from the socket and process it def process(self): """ Receive a subscription from the socket and process it """ subscription = None result = None try: subscription = self.socket.recv() except AuthenticateError as exception: loggi...
Encode, sign payload(optional) and attach subscription tag def build_payload(self, tag, message): """ Encode, sign payload(optional) and attach subscription tag """ message = self.encode(message) message = self.sign(message) payload = bytes(tag.encode('utf-8')) + message return ...
Publish a message down the socket def publish(self, tag, message): """ Publish a message down the socket """ payload = self.build_payload(tag, message) self.socket.send(payload)
Start a service def start_service(addr, n, authenticator): """ Start a service """ s = Subscriber(addr, authenticator=authenticator) def do_something(line): pass s.subscribe('test', do_something) started = time.time() for _ in range(n): s.process() s.socket.close() d...
Benchmark n requests def bench(client, n): """ Benchmark n requests """ items = list(range(n)) # Time client publish operations # ------------------------------ started = time.time() for i in items: client.publish('test', i) duration = time.time() - started print('Publisher cl...
Get the Webpack object for a given webpack config. Called at most once per request per config name. def get_webpack(request, name='DEFAULT'): """ Get the Webpack object for a given webpack config. Called at most once per request per config name. """ if not hasattr(request, '_webpack_map'): ...
Add pyramid_webpack methods and config to the app def includeme(config): """ Add pyramid_webpack methods and config to the app """ settings = config.registry.settings root_package_name = config.root_package.__name__ config.registry.webpack = { 'DEFAULT': WebpackState(settings, root_package_name...
Helper function to fetch settings, inheriting from the base def _get_setting(self, setting, default=None, name=None, inherit=True): """ Helper function to fetch settings, inheriting from the base """ if name is None: name = self.name if name == 'DEFAULT': return self._se...
Load and cache the webpack-stats file def load_stats(self, cache=None, wait=None): """ Load and cache the webpack-stats file """ if cache is None: cache = not self.debug if wait is None: wait = self.debug if not cache or self._stats is None: self._sta...
Load the webpack-stats file def _load_stats(self): """ Load the webpack-stats file """ for attempt in range(0, 3): try: with self.stats_file.open() as f: return json.load(f) except ValueError: # If we failed to parse the JSON, ...
Create a filter from the extensions and ignore files def _chunk_filter(self, extensions): """ Create a filter from the extensions and ignore files """ if isinstance(extensions, six.string_types): extensions = extensions.split() def _filter(chunk): """ Exclusion filter "...
Add a 'url' property to a chunk and return it def _add_url(self, chunk): """ Add a 'url' property to a chunk and return it """ if 'url' in chunk: return chunk public_path = chunk.get('publicPath') if public_path: chunk['url'] = public_path else: ...
Get all the chunks contained in a bundle def get_bundle(self, bundle_name, extensions=None): """ Get all the chunks contained in a bundle """ if self.stats.get('status') == 'done': bundle = self.stats.get('chunks', {}).get(bundle_name, None) if bundle is None: ra...
Generates unique sequences of bytes. def _unique_names(): """Generates unique sequences of bytes. """ characters = ("abcdefghijklmnopqrstuvwxyz" "0123456789") characters = [characters[i:i + 1] for i in irange(len(characters))] rng = random.Random() while True: letters ...
Escapes the path to a queue, e.g. preserves ~ at the begining. def escape_queue(s): """Escapes the path to a queue, e.g. preserves ~ at the begining. """ if isinstance(s, PosixPath): s = unicode_(s) elif isinstance(s, bytes): s = s.decode('utf-8') if s.startswith('~/'): retu...
Parses the SSH destination argument. def parse_ssh_destination(destination): """Parses the SSH destination argument. """ match = _re_ssh.match(destination) if not match: raise InvalidDestination("Invalid destination: %s" % destination) user, password, host, port = match.groups() info = ...
Gets an SSH client to connect with. def _ssh_client(self): """Gets an SSH client to connect with. """ ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.RejectPolicy()) return ssh
Connects via SSH. def _connect(self): """Connects via SSH. """ ssh = self._ssh_client() logger.debug("Connecting with %s", ', '.join('%s=%r' % (k, v if k != "password" else "***") for k, v in iteritems(self.destination))) ssh.c...
Gets the SSH client. This will check that the connection is still alive first, and reconnect if necessary. def get_client(self): """Gets the SSH client. This will check that the connection is still alive first, and reconnect if necessary. """ if self._ssh is No...
Calls a command through the SSH connection. Remote stderr gets printed to this program's stderr. Output is captured and may be returned. def _call(self, cmd, get_output): """Calls a command through the SSH connection. Remote stderr gets printed to this program's stderr. Output is capt...
Calls a command through SSH. def check_call(self, cmd): """Calls a command through SSH. """ ret, _ = self._call(cmd, False) if ret != 0: # pragma: no cover raise RemoteCommandFailure(command=cmd, ret=ret)
Calls a command through SSH and returns its output. def check_output(self, cmd): """Calls a command through SSH and returns its output. """ ret, output = self._call(cmd, True) if ret != 0: # pragma: no cover raise RemoteCommandFailure(command=cmd, ret=ret) logger.de...
Finds the location of tej's queue directory on the server. The `queue` set when constructing this `RemoteQueue` might be relative to the home directory and might contain ``~user`` placeholders. Also, each queue may in fact be a link to another path (a file containing the string ``tejdir...
Gets the actual location of the queue, or None. def _get_queue(self): """Gets the actual location of the queue, or None. """ if self._queue is None: self._links = [] queue, depth = self._resolve_queue(self.queue, links=self._links) if queue is None and depth ...
Installs the runtime at the target location. This will not replace an existing installation, unless `force` is True. After installation, creates links to this installation at the specified locations. def setup(self, links=None, force=False, only_links=False): """Installs the runtime a...
Actually installs the runtime. def _setup(self): """Actually installs the runtime. """ # Expands ~user in queue if self.queue.path[0:1] == b'/': queue = self.queue else: if self.queue.path[0:1] == b'~': output = self.check_output('echo %s'...
Submits a job to the queue. If the runtime is not there, it will be installed. If it is a broken chain of links, error. def submit(self, job_id, directory, script=None): """Submits a job to the queue. If the runtime is not there, it will be installed. If it is a broken chain o...
Gets the status of a previously-submitted job. def status(self, job_id): """Gets the status of a previously-submitted job. """ check_jobid(job_id) queue = self._get_queue() if queue is None: raise QueueDoesntExist ret, output = self._call('%s %s' % ( ...
Downloads files from server. def download(self, job_id, files, **kwargs): """Downloads files from server. """ check_jobid(job_id) if not files: return if isinstance(files, string_types): files = [files] directory = False recursive = kwarg...
Kills a job on the server. def kill(self, job_id): """Kills a job on the server. """ check_jobid(job_id) queue = self._get_queue() if queue is None: raise QueueDoesntExist ret, output = self._call('%s %s' % ( shell_escape(qu...
Lists the jobs on the server. def list(self): """Lists the jobs on the server. """ queue = self._get_queue() if queue is None: raise QueueDoesntExist output = self.check_output('%s' % shell_escape(queue / 'commands/list')) ...
Take a sequence of pairs specifying substitutions, and create a function that performs those substitutions. >>> multi_substitution(('foo', 'bar'), ('bar', 'baz'))('foo') 'baz' def multi_substitution(*substitutions): """ Take a sequence of pairs specifying substitutions, and create a function that performs those...
r""" Remove HTML from the string `s`. >>> str(simple_html_strip('')) '' >>> print(simple_html_strip('A <bold>stormy</bold> day in paradise')) A stormy day in paradise >>> print(simple_html_strip('Somebody <!-- do not --> tell the truth.')) Somebody tell the truth. >>> print(simple_html_strip('What about<br...
Remove the prefix from the text if it exists. >>> remove_prefix('underwhelming performance', 'underwhelming ') 'performance' >>> remove_prefix('something special', 'sample') 'something special' def remove_prefix(text, prefix): """ Remove the prefix from the text if it exists. >>> remove_prefix('underwhelming...
Remove the suffix from the text if it exists. >>> remove_suffix('name.git', '.git') 'name' >>> remove_suffix('something special', 'sample') 'something special' def remove_suffix(text, suffix): """ Remove the suffix from the text if it exists. >>> remove_suffix('name.git', '.git') 'name' >>> remove_suffix(...
Return the common prefix of two lines. def common_prefix(s1, s2): """ Return the common prefix of two lines. """ index = min(len(s1), len(s2)) while s1[:index] != s2[:index]: index -= 1 return s1[:index]
Run a graph and render the tag contents for each output def _get_graph(self, ctx, bundle, extensions, caller=None): """ Run a graph and render the tag contents for each output """ request = ctx.get('request') if request is None: request = get_current_request() if ':' in bund...
Switch to this project. def activate(lancet, method, project): """Switch to this project.""" with taskstatus("Looking up project") as ts: if method == "key": func = get_project_keys elif method == "dir": func = get_project_keys for key, project_path in func(lanc...
Start work on a given issue. This command retrieves the issue from the issue tracker, creates and checks out a new aptly-named branch, puts the issue in the configured active, status, assigns it to you and starts a correctly linked Harvest timer. If a branch with the same name as the one to be created...
Start an Harvest timer for the given issue. This command takes care of linking the timer with the issue tracker page for the given issue. If the issue is not passed to command it's taken from currently active branch. def time(lancet, issue): """ Start an Harvest timer for the given issue. Thi...
Pause work on the current issue. This command puts the issue in the configured paused status and stops the current Harvest timer. def pause(ctx): """ Pause work on the current issue. This command puts the issue in the configured paused status and stops the current Harvest timer. """ l...
Resume work on the currently active issue. The issue is retrieved from the currently active branch name. def resume(ctx): """ Resume work on the currently active issue. The issue is retrieved from the currently active branch name. """ lancet = ctx.obj username = lancet.tracker.whoami() ...
SSH into the given environment, based on the dploi configuration. def ssh(lancet, print_cmd, environment): """ SSH into the given environment, based on the dploi configuration. """ namespace = {} with open(lancet.config.get('dploi', 'deployment_spec')) as fh: code = compile(fh.read(), 'dep...
Print the shell integration code. def _setup_helper(): """Print the shell integration code.""" base = os.path.abspath(os.path.dirname(__file__)) helper = os.path.join(base, "helper.sh") with open(helper) as fh: click.echo(fh.read())
Prints a list of commands for shell completion hooks. def _commands(ctx): """Prints a list of commands for shell completion hooks.""" ctx = ctx.parent ctx.show_hidden_subcommands = False main = ctx.command for subcommand in main.list_commands(ctx): cmd = main.get_command(ctx, subcommand) ...
Prints a list of arguments for shell completion hooks. If a command name is given, returns the arguments for that subcommand. The command name has to refer to a command; aliases are not supported. def _arguments(ctx, command_name=None): """Prints a list of arguments for shell completion hooks. If a c...
Print the shell autocompletion code. def _autocomplete(ctx, shell): """Print the shell autocompletion code.""" if not shell: shell = os.environ.get("SHELL", "") shell = os.path.basename(shell).lower() if not shell: click.secho( "Your shell could not be detected, please p...
Call Python 3 raise from or emulate it for Python 2 Args: exc_type (Any): Type of Exception message (str): Error message to display exc (BaseException): original exception Returns: None def raisefrom(exc_type, message, exc): # type: (Any, str, BaseException) -> None ""...
initial some instances for preparing to run test case @note: should not override @param parser: instance of TestCaseParser @param tracers: dict type for the instance of Tracer. Such as {"":tracer_obj} or {"192.168.0.1:5555":tracer_obj1, "192.168.0.2:5555":tracer_obj2} @param proj_i...
running case with mutil process to support selenium grid-mode(multiple web) and appium grid-mode(multiple devices). @param func: function object @param iterables: iterable objects def _run_grid_multiprocess(self, func, iterables): ''' running case with mutil process to support selenium gr...
running case with mutil process to support selenium grid-mode(multiple web) and appium grid-mode(multiple devices). @param func: function object @param iterables: iterable objects def _run_grid_multithread(self, func, iterables): ''' running case with mutil process to support selenium gri...
Set the environment for pyrunner def init_project_env(subject='Automation', proj_path = None, sysencoding = "utf-8", debug = False): ''' Set the environment for pyrunner ''' # if sysencoding: # set_sys_encode(sysencoding) if not proj_path: try: executab...
序列化 字符串--->实际效果是,为字符串,添加行号,返回字符串 Sampe usage: strs = ["", None, u"First-line\nSecond-line\nThird-line", u"没有换行符"] for s in strs: print "---" result = seqfy(s) print result print unseqfy(result) def seqfy(strs): ''' 序列化 字符串--->实际效果是,为字符串,添加...
步骤化 字符串 --->实际效果是, 依据 序列化的字符串,转换为 Step_%s_info 的字典, 返回字典 Sample usage: test_strs = [ "", None, u"First-line\nSecond-line\nThird-line", u'1.First-line\n2.Second-line\n3.Third-line\n', u'3.没有换行符', u'3.有换行符\n', "asdfasdfsdf", "1.asdf...
Sample usage: print map_function('set',alias_func = "ini_items");# -> ini_items print map_function('set',fw_action_addtion="action_steps_",bw_action_addtion="_for_upd",alias_func = "ini_items"); # -> action_steps_ini_items_for_upd print map_function('set(a=1,b=2,c=Test())',"action_steps_","_f...
执行系统命令,并等待执行完 @param listcmd: 执行的命令,列表格式 @param end_expects: 命令执行结束,在输出的最后一行,正则搜素期望值,并设置 结果标志 @param save2logfile: 设置执行过程,保存的日志 @param coding: 设置输出编码 def until_cmd(listcmd, end_expects=None, save2logfile=None, coding = encoding): ''' 执行系统命令,并等待执行完 ...
Calls the method until the return value is not False. def until(method, timeout = 30, message=''): """Calls the method until the return value is not False.""" end_time = time.time() + timeout while True: try: value = method() if value: ...
check testcase format if valid def _check_format(file_path, content): """ check testcase format if valid """ if not content: # testcase file content is empty err_msg = u"Testcase file content is empty: {}".format(file_path) raise p_exception.FileFormatE...
load yaml file and check file content format def _load_yaml_file(yaml_file): """ load yaml file and check file content format """ with io.open(yaml_file, 'r', encoding='utf-8') as stream: yaml_content = yaml.load(stream) FileUtils._check_format(yaml_file, yaml_conte...
load json file and check file content format def _load_json_file(json_file): """ load json file and check file content format """ with io.open(json_file, encoding='utf-8') as data_file: try: json_content = json.load(data_file) except p_exception.JSO...
load csv file and check file content format @param csv_file: csv file path e.g. csv file content: username,password test1,111111 test2,222222 test3,333333 @return list of parameter, each paramete...
force delete a file def force_delete_file(file_path): ''' force delete a file ''' if os.path.isfile(file_path): try: os.remove(file_path) return file_path except: return FileSystemUtils.add_unique_postfix(file_pat...
Usage: p = r'D:\auto\env\ttest\ins\build\lib\rock4\softtest\support' mkzip(os.path.join(p, "appiumroot"),os.path.join(p, "appiumroot.zip")) unzip(os.path.join(p, "appiumroot.zip"),os.path.join(p, "appiumroot2")) def mkzip(source_dir, output_filename): '''Usage: ...
import module from python file path and return imported module def get_imported_module_from_file(file_path): """ import module from python file path and return imported module """ if p_compat.is_py3: imported_module = importlib.machinery.SourceFileLoader('module_name', file_path...
filter functions or variables from import module @params module: imported module filter_type: "function" or "variable" def filter_module(module, filter_type): """ filter functions or variables from import module @params module: imported module ...
search expected function or variable recursive upward @param start_path: search start path item_type: "function" or "variable" item_name: function name or variable name e.g. search_conf_item('C:/Users/RockFeng/Desktop/s/preference.py','function','tes...
Locates the specified data-files and returns the matches; filesystem tree for setup's data_files in setup.py Usage: data_files = find_data_files(r"C:\Python27\Lib\site-packages\numpy\core","numpy/core",["*.dll","*.pyd"]) data_files = find_data_files(r"d:\auto...
convert mapping in list to ordered dict @param (list) map_list [ {"a": 1}, {"b": 2} ] @return (OrderDict) OrderDict({ "a": 1, "b": 2 }) def convert_to_order_dict(map_list): ...
initial the configuration with file that you specify Sample usage: config = get_value_from_cfg() return: return a dict -->config[section][option] such as config["twsm"]["dut_ip"] def get_value_from_cfg(cfg_file): ''' ...
Get the exception info Sample usage: try: raise Exception("asdfsdfsdf") except: print common.get_exception_error() Return: return the exception infomation. def get_exception_error(): ''' Get the exception info ...
usage: for i in range(101): ProgressBarUtils.echo(i,100) def echo(transferred, toBeTransferred, suffix=''): ''' usage: for i in range(101): ProgressBarUtils.echo(i,100) ''' bar_len = 60 rate = transferred/fl...
Sample usage: f=lambda x,y:x+y ldata = range(10) toBeTransferred = reduce(f,range(10)) progress = ProgressBarUtils("refresh", toBeTransferred=toBeTransferred, unit="KB", chunk_size=1.0, run_status="正在下载", fin_status="下载完成") imp...
Sample usage: f=lambda x,y:x+y ldata = range(10) toBeTransferred = reduce(f,range(10)) import time progress = ProgressBarUtils("viewbar", toBeTransferred=toBeTransferred, run_status="正在下载", fin_status="下载完成") for i in ldata:...
Start a service def start_service(addr, n): """ Start a service """ s = Service(addr) s.register('add', lambda x, y: x + y) started = time.time() for _ in range(n): s.process() duration = time.time() - started time.sleep(0.1) print('Service stats:') util.print_stats(n, dur...
Benchmark n requests def bench(client, n): """ Benchmark n requests """ pairs = [(x, x + 1) for x in range(n)] started = time.time() for pair in pairs: res, err = client.call('add', *pair) # assert err is None duration = time.time() - started print('Client stats:') util.pri...
Start a service def start_service(addr, n): """ Start a service """ s = Subscriber(addr) s.socket.set_string_option(nanomsg.SUB, nanomsg.SUB_SUBSCRIBE, 'test') started = time.time() for _ in range(n): msg = s.socket.recv() s.socket.close() duration = time.time() - started pri...
r"""Given bl"a, returns "bl\\"a". def shell_escape(s): r"""Given bl"a, returns "bl\\"a". """ if isinstance(s, PosixPath): s = unicode_(s) elif isinstance(s, bytes): s = s.decode('utf-8') if not s or any(c not in safe_shell_chars for c in s): return '"%s"' % (s.replace('\\', ...
List Harvest projects, optionally filtered with a regexp. def projects(lancet, query): """List Harvest projects, optionally filtered with a regexp.""" projects = lancet.timer.projects() if query: regexp = re.compile(query, flags=re.IGNORECASE) def match(project): match = regex...
List Harvest tasks for the given project ID. def tasks(lancet, project_id): """List Harvest tasks for the given project ID.""" for task in lancet.timer.tasks(project_id): click.echo('{:>9d} {} {}'.format( task['id'], click.style('‣', fg='yellow'), task['name']))
Retrieve the long description from DESCRIPTION.rst def get_long_description(): """ Retrieve the long description from DESCRIPTION.rst """ here = os.path.abspath(os.path.dirname(__file__)) with copen(os.path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as description: return description.read()
Flattens a list, ignore all the lambdas. def flatten(nested_list: list) -> list: """Flattens a list, ignore all the lambdas.""" return list(sorted(filter(lambda y: y is not None, list(map(lambda x: (nested_list.extend(x) # noqa: T484 ...
Get all .py files. def get_py_files(dir_name: str) -> list: """Get all .py files.""" return flatten([ x for x in [["{0}/{1}".format(path, f) for f in files if f.endswith(".py")] for path, _, files in os.walk(dir_name) if not path.startswith("./build")] if x ])
Raise SystemExit with correct status code and output logs. def exit(self) -> None: """Raise SystemExit with correct status code and output logs.""" total = sum(len(logs) for logs in self.logs.values()) if self.json: self.logs['total'] = total print(json.dumps(self.logs, ...
Run a checker class def run_linter(self, linter) -> None: """Run a checker class""" self.current = linter.name if (linter.name not in self.parser["all"].as_list("linters") or linter.base_pyversion > sys.version_info): # noqa: W503 return if any(x not in se...
Try to read a rcfile from a list of paths def read_rcfile(): """ Try to read a rcfile from a list of paths """ files = [ '{}/.millipederc'.format(os.environ.get('HOME')), '/usr/local/etc/millipederc', '/etc/millipederc', ] for filepath in files: if os.path.isfile...
Parses rcfile Invalid lines are ignored with a warning def parse_rcfile(rcfile): """ Parses rcfile Invalid lines are ignored with a warning """ def parse_bool(value): """Parse boolean string""" value = value.lower() if value in ['yes', 'true']: return True ...