code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
from __future__ import absolute_import import time import sys import os import json import inspect import threading import traceback import logging import opentracing from opentracing.ext import tags as opentracing_tags from opentracing.propagation import SpanContextCorruptedException import datetime from .utils import gethostname,local_ip from .span_context import SpanContext from .constants import SAMPLED_FLAG, DEBUG_FLAG, APPTRACK_HOSTNAME_TAG_KEY, APPTRACK_IPV4_TAG_KEY from . import codecs from .thrift import make_string_tag, make_tags, make_log import slugify import traceback import StringIO import six LOG_RING_DEFAULT = 'system_manager' LOG_LEVEL_DBG = logging.getLevelName(logging.DEBUG) LOG_LEVEL_INFO = logging.getLevelName(logging.INFO) LOG_LEVEL_WARN = logging.getLevelName(logging.WARNING) LOG_LEVEL_ERROR = logging.getLevelName(logging.ERROR) LOG_LEVEL_FAULT = logging.getLevelName(logging.FATAL) LOG_LEVEL_EXCEPTION = 'EXCEPTION' class Span(opentracing.Span): __slots__ = ['_tracer', '_context', 'operation_name', 'start_time', 'end_time', 'logs', 'tags', 'update_lock'] def __init__(self, context, tracer, operation_name=None, tags=None, start_time=None,log_rings = []): super(Span, self).__init__(context=context, tracer=tracer) self.operation_name = operation_name self.start_time = start_time or datetime.datetime.utcnow() self.end_time = None self.update_lock = threading.Lock() self.tags = [(opentracing_tags.ERROR,False),(APPTRACK_HOSTNAME_TAG_KEY,gethostname()),(APPTRACK_IPV4_TAG_KEY,local_ip())] self.log_rings = log_rings if tags: for k, v in six.iteritems(tags): self.tags.append([k,v]) if not self.log_rings: self.log_rings = [LOG_RING_DEFAULT] def start(self): self.tracer.report_span(self) def finish(self, finish_time=None,error=False,**kwargs): if not self.is_sampled(): return self.end_time = finish_time or datetime.datetime.utcnow() if error: exc_type, exc_value, exc_traceback = sys.exc_info() Span._on_error(self, exc_type, exc_value, exc_traceback) self.set_tags(kwargs) self.tracer.finish_span(self) def set_operation_name(self, operation_name): self.operation_name = operation_name self.tracer.set_span_name(self.span_id,self.operation_name) return opentracing.Span.set_operation_name(self,operation_name) @property def context(self): """Provides access to the SpanContext associated with this Span. The SpanContext contains state that propagates from Span to Span in a larger trace. :return: returns the SpanContext associated with this Span. """ return self._context @property def tracer(self): """Provides access to the Tracer that created this Span. :return: returns the Tracer that created this Span. """ return self._tracer @property def trace_id(self): return self.context.trace_id @property def span_id(self): return self.context.span_id @property def parent_id(self): return self.context.parent_id @property def flags(self): return self.context.flags def is_sampled(self): return self.context.flags & SAMPLED_FLAG == SAMPLED_FLAG def is_debug(self): return self.context.flags & DEBUG_FLAG == DEBUG_FLAG def __repr__(self): print self.context.trace_id,self.context.span_id,self.context.parent_id,self.context.flags c = codecs.span_context_to_string(trace_id=self.context.trace_id,span_id=self.context.span_id, parent_id=self.context.parent_id, flags=self.context.flags) return '%s %s.%s' % (c, self.tracer.service_name, self.operation_name) def set_tag(self, key, value): with self.update_lock: if key == opentracing_tags.SAMPLING_PRIORITY: if value > 0: self.context.flags |= SAMPLED_FLAG | DEBUG_FLAG else: self.context.flags &= ~SAMPLED_FLAG else: tag = make_string_tag( key=key, value=str(value), max_length=self.tracer.max_tag_value_length, ) #self.tags.append(tag) self.tracer.reporter.put_tag(self,key,value) return self def set_tags(self,tags): for k,v in tags.items(): self.tracer.reporter.put_tag(self,k,v) return self def list_tags(self): return [t for t, v in self.tracer.taskdb().sdb.keys("/" + self.spanid, with_value=False)] def _logger(self, log_ring, log_level, content): assert(type(log_ring) == list) if self.is_debug(): print "{ring}:{level} {content}" \ .format(ring=log_ring,level=log_level,content=content) self.log_kv({ opentracing.span.logs.EVENT:log_level, opentracing.span.logs.MESSAGE:content, 'ring':log_ring }) def logger(self,log_ring=[]): class span_logger: def __init__(self, ring, log_handle): self.log_ring = ring self.log = log_handle def debug(self, msg): self.log(self.log_ring, LOG_LEVEL_DBG,msg) def info(self, msg): self.log(self.log_ring, LOG_LEVEL_INFO,msg) def warn(self, msg): self.log(self.log_ring, LOG_LEVEL_WARN,msg) def error(self, msg): self.log(self.log_ring, LOG_LEVEL_ERROR,msg) def exception(self, msg=''): self.log(self.log_ring, LOG_LEVEL_EXCEPTION,msg) def fault(self, msg): self.log(self.log_ring, LOG_LEVEL_FAULT,msg) return span_logger(log_ring if log_ring else self.log_rings[0:1], self._logger) def log_kv(self, key_values, timestamp=None): timestamp = timestamp if timestamp else time.time() log = make_log( timestamp=timestamp if timestamp else time.time(), fields=key_values, max_length=self._tracer.max_tag_value_length, ) # 下面的代码将获取对log_kv函数的调用者信息,已追加进日志记录中 stacks = inspect.stack() if len(stacks) < 2: caller_fn = "Unkown" line_no = 0 file_name = "Unkown" else: try: caller_class_self = stacks[1][0].f_locals.get("self", None) if caller_class_self == None: caller_fn = stacks[1][3] + '(...)' else: caller_fn = caller_class_self.__class__.__name__ + '.' + stacks[1][3] + '(...)' except: caller_fn = "Unkown" line_no = stacks[1][2] file_name = stacks[1][1] # key_values.update({'caller_fn': caller_fn, 'line_no': line_no, 'file_name': file_name, "timestamp": timestamp}) # 为每个log条目分配一个全局id号,注意如果多个进场都在向同一个span进行日志输出,那么,有可能这些id号是不连续的,因此为了让 # log日志能按照时间顺序排列,我们还要在日志id号前面加上时间戳数据,此外, 通过spanid作为前缀的id号,我们将裁掉前面的spanid前缀,只保留后面的id # sorting logs default_event= self.operation_name if self.operation_name else 'other' event=key_values.pop(opentracing.span.logs.EVENT, default_event) message = key_values.pop(opentracing.span.logs.MESSAGE) self._tracer.reporter.put_log(self.span_id,event,message,rings=key_values.pop('ring'),**key_values) return self def set_baggage_item(self, key, value): prev_value = self.get_baggage_item(key=key) new_context = self.context.with_baggage_item(key=key, value=value) self._context = new_context logs = { 'event': 'baggage', 'key': key, 'value': value, 'message':'set span %s baggage item'%self.span_id, 'ring':self.log_rings[0:1] } if prev_value: logs['override'] = True self.log_kv(key_values=logs) self._tracer.reporter.update_context(self._context) return self def set_baggage(self, baggage): for k,v in baggage.items(): self.set_baggage_item(k,v) def get_baggage_item(self, key): return self.context.baggage.get(key) def __enter__(self): """Invoked when span is used as a context manager. :return: returns the Span itself """ return self def __exit__(self, exc_type, exc_val, exc_tb): """Ends context manager and calls finish() on the span. If exception has occurred during execution, it is automatically added as a tag to the span. """ Span._on_error(self, exc_type, exc_val, exc_tb) self.finish() @staticmethod def _on_error(span, exc_type, exc_val, exc_tb): if not span or not exc_type: return io_err = StringIO.StringIO() io_err.write('--- Logging exception ---\n') traceback.print_exception(exc_type, exc_val, exc_tb, None, io_err) io_err.write('Call stack:\n') span.set_tag(opentracing_tags.ERROR, True) span.log_kv({ opentracing.span.logs.EVENT: LOG_LEVEL_EXCEPTION, opentracing.span.logs.MESSAGE: str(exc_val), opentracing.span.logs.ERROR_OBJECT: str(exc_val), opentracing.span.logs.ERROR_KIND: str(exc_type), opentracing.span.logs.STACK: io_err.getvalue(), 'ring':span.log_rings }) io_err.close() def spanid_to_span(tracer, span_id, need_record_where_it_is=False, need_wait_events_collector=None): if need_record_where_it_is: timestamp = time.time() key_values = {} self.log_kv({'event':[LOG_RING_0,LOG_LEVEL_INFO], 'layload':json.dumps(key_values), 'timestamp':timestamp, }) trace_id=tracer.trace_id ctx = tracer.get_context(span_id) if ctx is None: ctx = SpanContext(trace_id=trace_id, span_id=span_id, parent_id=0) else: assert(str(ctx['trace_id']) == str(trace_id)) ctx = SpanContext(trace_id=trace_id, span_id=span_id, parent_id=ctx.get('parent_id',None),flags=ctx['flags'],baggage=ctx['baggage']) return Span(ctx,tracer)
AppTrack
/AppTrack-1.0.tar.gz/AppTrack-1.0/apptrack/span.py
span.py
from __future__ import absolute_import from future import standard_library standard_library.install_aliases() # noqa from builtins import object from past.builtins import basestring from opentracing import ( InvalidCarrierException, SpanContextCorruptedException, ) from .constants import ( BAGGAGE_HEADER_PREFIX, DEBUG_ID_HEADER_KEY, TRACE_ID_HEADER, ) from .span_context import SpanContext from .constants import SAMPLED_FLAG, DEBUG_FLAG import six import urllib.parse import json import struct class Codec(object): def inject(self, span_context, carrier): raise NotImplementedError() def extract(self, carrier): raise NotImplementedError() class TextCodec(Codec): def __init__(self, url_encoding=False, trace_id_header=TRACE_ID_HEADER, baggage_header_prefix=BAGGAGE_HEADER_PREFIX, debug_id_header=DEBUG_ID_HEADER_KEY): self.url_encoding = url_encoding self.trace_id_header = trace_id_header.lower().replace('_', '-') self.baggage_prefix = baggage_header_prefix.lower().replace('_', '-') self.debug_id_header = debug_id_header.lower().replace('_', '-') self.prefix_length = len(baggage_header_prefix) def inject(self, span_context, carrier): if not isinstance(carrier, dict): raise InvalidCarrierException('carrier not a collection') carrier[self.trace_id_header] = span_context_to_string( trace_id=span_context.trace_id, span_id=span_context.span_id, parent_id=span_context.parent_id, flags=span_context.flags) baggage = span_context.baggage if baggage: for key, value in six.iteritems(baggage): encoded_key = key if self.url_encoding: #python2需要将value转换成字节 encoded_value = urllib.parse.quote(bytes(value)) if six.PY2 and isinstance(key, six.text_type): encoded_key = key.encode('utf-8') else: encoded_value = value header_key = '%s%s' % (self.baggage_prefix, encoded_key) carrier[header_key] = encoded_value def extract(self, carrier): if not hasattr(carrier, 'items'): raise InvalidCarrierException('carrier not a collection') trace_id, span_id, parent_id, flags = None, None, None, None baggage = None debug_id = None for key, value in six.iteritems(carrier): uc_key = key.lower() if uc_key == self.trace_id_header: if self.url_encoding: value = urllib.parse.unquote(value) trace_id, span_id, parent_id, flags = \ span_context_from_string(value) elif uc_key.startswith(self.baggage_prefix): if self.url_encoding: value = urllib.parse.unquote(value) attr_key = key[self.prefix_length:] if baggage is None: baggage = {attr_key.lower(): value} else: baggage[attr_key.lower()] = value elif uc_key == self.debug_id_header: if self.url_encoding: value = urllib.parse.unquote(value) debug_id = value if not trace_id and baggage: raise SpanContextCorruptedException('baggage without trace ctx') if not trace_id: if debug_id is not None: return SpanContext.with_debug_id(debug_id=debug_id) return None return SpanContext(trace_id=trace_id, span_id=span_id, parent_id=parent_id, flags=flags, baggage=baggage) class BinaryCodec(Codec): def __init__(self, trace_id_header=TRACE_ID_HEADER): self.trace_id_header = trace_id_header.lower().replace('_', '-') def inject(self, span_context, carrier): if not isinstance(carrier, bytearray): raise InvalidCarrierException('carrier not a bytearray') baggage = span_context.baggage.copy() baggage[self.trace_id_header] = span_context_to_string( trace_id=span_context.trace_id, span_id=span_context.span_id, parent_id=span_context.parent_id, flags=span_context.flags) bin_baggage = bytearray(json.dumps(baggage)) carrier.extend(bytearray(struct.pack("I", len(bin_baggage)))) carrier.extend(bin_baggage) def extract(self, carrier): if not isinstance(carrier, bytearray): raise InvalidCarrierException('carrier not a bytearray') ctx_len = struct.unpack('I', carrier[0:4])[0] carrier = json.loads(str(carrier[4:4 + ctx_len])) trace_id, span_id, parent_id, flags = None, None, None, None baggage = None for key, value in six.iteritems(carrier): uc_key = key.lower() if uc_key == self.trace_id_header: trace_id, span_id, parent_id, flags = \ span_context_from_string(value) else: if baggage is None: baggage = {uc_key: value} else: baggage[uc_key] = value if baggage == None or (not isinstance(baggage, dict)): raise SpanContextCorruptedException() return SpanContext(trace_id=trace_id, span_id=span_id, parent_id=parent_id, flags=flags, baggage=baggage) def span_context_to_string(trace_id, span_id, parent_id, flags): """ Serialize span ID to a string {trace_id}:{span_id}:{parent_id}:{flags} Numbers are encoded as variable-length lower-case hex strings. If parent_id is None, it is written as 0. :param trace_id: :param span_id: :param parent_id: :param flags: """ parent_id = parent_id or 0 def convert_id_to_int(_id): if type(_id) == str: if is_hex_str(_id): _id = int(_id,16) else: _id = int(_id) assert(type(_id)==int or type(_id)==long) return _id trace_id = convert_id_to_int(trace_id) span_id = convert_id_to_int(span_id) parent_id = convert_id_to_int(parent_id) flags = convert_id_to_int(flags) #转换为16进制数 return '{:x}:{:x}:{:x}:{:x}'.format(trace_id, span_id, parent_id, flags) def span_context_from_string(value): """ Decode span ID from a string into a TraceContext. Returns None if the string value is malformed. :param value: formatted {trace_id}:{span_id}:{parent_id}:{flags} """ if type(value) is list and len(value) > 0: # sometimes headers are presented as arrays of values if len(value) > 1: raise SpanContextCorruptedException( 'trace context must be a string or array of 1: "%s"' % value) value = value[0] if not isinstance(value, basestring): raise SpanContextCorruptedException( 'trace context not a string "%s"' % value) parts = value.split(':') if len(parts) != 4: raise SpanContextCorruptedException( 'malformed trace context "%s"' % value) try: trace_id = int(parts[0], 16) span_id = int(parts[1], 16) parent_id = int(parts[2], 16) flags = int(parts[3], 16) if trace_id < 1 or span_id < 1 or parent_id < 0 or flags < 0: raise SpanContextCorruptedException( 'malformed trace context "%s"' % value) if parent_id == 0: parent_id = None return trace_id, span_id, parent_id, flags except ValueError as e: raise SpanContextCorruptedException( 'malformed trace context "%s": %s' % (value, e)) def header_to_hex(header): if not isinstance(header, (str, six.text_type)): raise SpanContextCorruptedException( 'malformed trace context "%s", expected hex string' % header) try: return int(header, 16) except ValueError: raise SpanContextCorruptedException( 'malformed trace context "%s", expected hex string' % header) def is_hex_str(txt): digits = '0123456789abcdef' for i in txt.lower(): if i not in digits: raise RuntimeError("error hex alphabet") elif i in digits[10:]: return True return False
AppTrack
/AppTrack-1.0.tar.gz/AppTrack-1.0/apptrack/codecs.py
codecs.py
from __future__ import absolute_import from __future__ import division from builtins import object import json import logging import random import six from threading import Lock from .constants import ( MAX_ID_BITS, DEFAULT_SAMPLING_INTERVAL, SAMPLER_TYPE_CONST, SAMPLER_TYPE_PROBABILISTIC, SAMPLER_TYPE_RATE_LIMITING, SAMPLER_TYPE_LOWER_BOUND, ) from .metrics import Metrics, LegacyMetricsFactory default_logger = logging.getLogger(__name__) SAMPLER_TYPE_TAG_KEY = 'sampler.type' SAMPLER_PARAM_TAG_KEY = 'sampler.param' DEFAULT_SAMPLING_PROBABILITY = 0.001 DEFAULT_LOWER_BOUND = 1.0 / (10.0 * 60.0) # sample once every 10 minutes DEFAULT_MAX_OPERATIONS = 2000 STRATEGIES_STR = 'perOperationStrategies' OPERATION_STR = 'operation' DEFAULT_LOWER_BOUND_STR = 'defaultLowerBoundTracesPerSecond' PROBABILISTIC_SAMPLING_STR = 'probabilisticSampling' SAMPLING_RATE_STR = 'samplingRate' DEFAULT_SAMPLING_PROBABILITY_STR = 'defaultSamplingProbability' OPERATION_SAMPLING_STR = 'operationSampling' MAX_TRACES_PER_SECOND_STR = 'maxTracesPerSecond' RATE_LIMITING_SAMPLING_STR = 'rateLimitingSampling' STRATEGY_TYPE_STR = 'strategyType' class Sampler(object): """ Sampler is responsible for deciding if a particular span should be "sampled", i.e. recorded in permanent storage. """ def __init__(self, tags=None): self._tags = tags def is_sampled(self, trace_id, operation=''): raise NotImplementedError() def close(self): raise NotImplementedError() def __eq__(self, other): return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) def __ne__(self, other): return not self.__eq__(other) class ConstSampler(Sampler): """ConstSampler always returns the same decision.""" def __init__(self, decision): super(ConstSampler, self).__init__( tags={ SAMPLER_TYPE_TAG_KEY: SAMPLER_TYPE_CONST, SAMPLER_PARAM_TAG_KEY: decision, } ) self.decision = decision def is_sampled(self, trace_id, operation=''): return self.decision, self._tags def close(self): pass def __str__(self): return 'ConstSampler(%s)' % self.decision class ProbabilisticSampler(Sampler): """ A sampler that randomly samples a certain percentage of traces specified by the samplingRate, in the range between 0.0 and 1.0. It relies on the fact that new trace IDs are 64bit random numbers themselves, thus making the sampling decision without generating a new random number, but simply calculating if traceID < (samplingRate * 2^64). Note that we actually ignore (zero out) the most significant bit. """ def __init__(self, rate): super(ProbabilisticSampler, self).__init__( tags={ SAMPLER_TYPE_TAG_KEY: SAMPLER_TYPE_PROBABILISTIC, SAMPLER_PARAM_TAG_KEY: rate, } ) assert 0.0 <= rate <= 1.0, 'Sampling rate must be between 0.0 and 1.0' self.rate = rate self.max_number = 1 << MAX_ID_BITS self.boundary = rate * self.max_number def is_sampled(self, trace_id, operation=''): return trace_id < self.boundary, self._tags def close(self): pass def __str__(self): return 'ProbabilisticSampler(%s)' % self.rate class RateLimitingSampler(Sampler): """ Samples at most max_traces_per_second. The distribution of sampled traces follows burstiness of the service, i.e. a service with uniformly distributed requests will have those requests sampled uniformly as well, but if requests are bursty, especially sub-second, then a number of sequential requests can be sampled each second. """ def __init__(self, max_traces_per_second=10): super(RateLimitingSampler, self).__init__( tags={ SAMPLER_TYPE_TAG_KEY: SAMPLER_TYPE_RATE_LIMITING, SAMPLER_PARAM_TAG_KEY: max_traces_per_second, } ) assert max_traces_per_second >= 0, \ 'max_traces_per_second must not be negative' self.traces_per_second = max_traces_per_second self.rate_limiter = RateLimiter( credits_per_second=self.traces_per_second, max_balance=self.traces_per_second if self.traces_per_second > 1.0 else 1.0 ) def is_sampled(self, trace_id, operation=''): return self.rate_limiter.check_credit(1.0), self._tags def close(self): pass def __eq__(self, other): """The last_tick and balance fields can be different""" if not isinstance(other, self.__class__): return False d1 = dict(self.rate_limiter.__dict__) d2 = dict(other.rate_limiter.__dict__) d1['balance'] = d2['balance'] d1['last_tick'] = d2['last_tick'] return d1 == d2 def __str__(self): return 'RateLimitingSampler(%s)' % self.traces_per_second class GuaranteedThroughputProbabilisticSampler(Sampler): def __init__(self, operation, lower_bound, rate): super(GuaranteedThroughputProbabilisticSampler, self).__init__( tags={ SAMPLER_TYPE_TAG_KEY: SAMPLER_TYPE_LOWER_BOUND, SAMPLER_PARAM_TAG_KEY: rate, } ) self.probabilistic_sampler = ProbabilisticSampler(rate) self.lower_bound_sampler = RateLimitingSampler(lower_bound) self.operation = operation self.rate = rate self.lower_bound = lower_bound def is_sampled(self, trace_id, operation=''): sampled, tags = \ self.probabilistic_sampler.is_sampled(trace_id, operation) if sampled: self.lower_bound_sampler.is_sampled(trace_id, operation) return True, tags sampled, _ = self.lower_bound_sampler.is_sampled(trace_id, operation) return sampled, self._tags def close(self): self.probabilistic_sampler.close() self.lower_bound_sampler.close() def update(self, lower_bound, rate): # (NB) This function should only be called while holding a Write lock. if self.rate != rate: self.probabilistic_sampler = ProbabilisticSampler(rate) self.rate = rate self._tags = { SAMPLER_TYPE_TAG_KEY: SAMPLER_TYPE_LOWER_BOUND, SAMPLER_PARAM_TAG_KEY: rate, } if self.lower_bound != lower_bound: self.lower_bound_sampler = RateLimitingSampler(lower_bound) self.lower_bound = lower_bound def __str__(self): return 'GuaranteedThroughputProbabilisticSampler(%s, %f, %f)' \ % (self.operation, self.rate, self.lower_bound) def get_sampling_probability(strategy=None): if not strategy: return DEFAULT_SAMPLING_PROBABILITY probability_strategy = strategy.get(PROBABILISTIC_SAMPLING_STR) if not probability_strategy: return DEFAULT_SAMPLING_PROBABILITY return probability_strategy.get(SAMPLING_RATE_STR, DEFAULT_SAMPLING_PROBABILITY) def get_rate_limit(strategy=None): if not strategy: return DEFAULT_LOWER_BOUND rate_limit_strategy = strategy.get(RATE_LIMITING_SAMPLING_STR) if not rate_limit_strategy: return DEFAULT_LOWER_BOUND return rate_limit_strategy.get(MAX_TRACES_PER_SECOND_STR, DEFAULT_LOWER_BOUND)
AppTrack
/AppTrack-1.0.tar.gz/AppTrack-1.0/apptrack/sampler.py
sampler.py
from builtins import bytes from builtins import range from builtins import object import platform import socket import struct import time import threading class ErrorReporter(object): """ Reports errors by emitting metrics, and if logger is provided, logging the error message once every log_interval_minutes N.B. metrics will be deprecated in the future """ def __init__(self, logger=None, log_interval_minutes=15): self.logger = logger self.log_interval_minutes = log_interval_minutes self._last_error_reported_at = time.time() def error(self, *args): if self.logger is None: return next_logging_deadline = \ self._last_error_reported_at + (self.log_interval_minutes * 60) current_time = time.time() if next_logging_deadline >= current_time: # If we aren't yet at the next logging deadline return self.logger.error(*args) self._last_error_reported_at = current_time def get_boolean(string, default): string = str(string).lower() if string in ['false', '0', 'none']: return False elif string in ['true', '1']: return True else: return default def gethostname(): return socket.gethostname() if platform.system().lower().find("windows") != -1: def local_ip(): """ 查询本机ip地址 :return: ip """ try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) ip = s.getsockname()[0] finally: s.close() return ip elif platform.system().lower().find("linux") != -1: import fcntl def local_ip(): """Get the local network IP of this machine""" try: ip = socket.gethostbyname(gethostname()) except IOError: ip = socket.gethostbyname('localhost') if ip.startswith('127.'): # Check eth0, eth1, eth2, en0, ... interfaces = [ i + str(n) for i in ('eth', 'en', 'wlan') for n in range(3) ] # :( for interface in interfaces: try: ip = interface_ip(interface) break except IOError: pass return ip def interface_ip(interface): """Determine the IP assigned to us by the given network interface.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa( fcntl.ioctl( sock.fileno(), 0x8915, struct.pack('256s', interface[:15]) )[20:24] ) # Explanation: # http://stackoverflow.com/questions/11735821/python-get-localhost-ip # http://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-of-eth0-in-python def ip2long(ip): packedIP = socket.inet_aton(ip) return struct.unpack("!L", packedIP)[0]
AppTrack
/AppTrack-1.0.tar.gz/AppTrack-1.0/apptrack/utils.py
utils.py
from libcloud.base import singleton from ConfigParser import ConfigParser import os import time def GetDynamicImportModule(full_module_path): ''' 从给定字符串中动态获取模块的类 ''' #必须先导入模块,再获取模块里面的方法,不要直接导入类 #如果类名是类似xx.yy.zz这样的,必须设置fromlist不为空 module_obj = __import__(full_module_path,globals(), globals(), fromlist=['__name__']) return module_obj class TraceDb: ''' ''' MONGODB_ENGINE = "backend.mongo" #表示该类是单例类 #数据库引擎列表 DRIVERS = [ MONGODB_ENGINE, ] __metaclass__ = singleton.Singleton default_database_engine = None def __init__(self): self.database_engines = {} for db_engine_name in TraceDb.DRIVERS: database_engine_module = GetDynamicImportModule(db_engine_name) self.database_engines[db_engine_name] = database_engine_module def set_default_backend(self,default_backend,**kwargs): if not default_backend in self.database_engines: raise RuntimeError("error backend name %s"%default_backend) TraceDb.default_database_engine = default_backend self.database_engines[default_backend].init(**kwargs) def put_tag(self,span_id,key,value): self.database_engines[self.default_database_engine].put_tag(span_id,key,value) def put_log(self,span_id,level,msg,rings=[],**kwargs): self.database_engines[self.default_database_engine].put_log(span_id,level,msg,rings,**kwargs) def finish_span(self,span_id): self.database_engines[self.default_database_engine].finish_span(span_id) def start_span(self,span_id,parent_id=None,tags=[],context=None): self.database_engines[self.default_database_engine].start_span(span_id,parent_id,tags,context) def set_span_name(self,span_id,name): self.database_engines[self.default_database_engine].set_span_name(span_id,name) @classmethod def get_db(cls): return cls() def create_span_id(self): if not self.default_database_engine: raise RuntimeError("error!could not find default trace backend") return self.database_engines[self.default_database_engine].create_new_id() def form_span_id(self,span_id): return self.database_engines[self.default_database_engine].form_span_id(span_id) def get_span_info(self,span_id,contain_child=False): return self.database_engines[self.default_database_engine].get_span_info(span_id,contain_child) def get_span_logs(self,span_id,timestamp=None,log_ring=None): return self.database_engines[self.default_database_engine].get_span_logs(span_id,timestamp,log_ring) def get_span_context(self,span_id): return self.database_engines[self.default_database_engine].get_span_context(span_id) def update_context(self,context): self.database_engines[self.default_database_engine].update_context(context)
AppTrack
/AppTrack-1.0.tar.gz/AppTrack-1.0/apptrack/db.py
db.py
import json import os import datetime import time from mongoengine import * import copy import slugify def init(**kwargs): for k, v in kwargs.items(): conn_params = copy.deepcopy(v) name = conn_params.pop('name') register_connection(k, name, **conn_params) #默认30天过期 EXPIRED_SECONDS = 3600*24*30 COMMON_EXPIRED_INDEX = { 'fields': ['created_at'], 'expireAfterSeconds': EXPIRED_SECONDS } class Span(Document): start_time = DateTimeField() end_time = DateTimeField() name = StringField(max_length=200) parent_id = ObjectIdField() created_at = DateTimeField(required=True,default=datetime.datetime.utcnow) meta = { 'db_alias':'default', 'indexes':[ COMMON_EXPIRED_INDEX ] } @staticmethod def get_span(span_id): span = Span.objects(id=span_id).first() if span is None: raise RuntimeError("span id %s is not exist"%span_id) return span @staticmethod def make_mongo_dict(kwargs): d = {} for k,v in kwargs.items(): d[slugify.slugify(k, separator='_')] = v return d def create_new_id(): ''' ''' span = Span() span.save() return str(span.id) def put_tag(span_id,key,value): ''' ''' span = Span.get_span(span_id) names = [key] values = [value] for tag in Tag.objects(span_id=span_id): tag_names = tag.name tag_values = tag.value if key == tag_names[0] and value == tag_values[0]: return elif key == tag_names[0]: i = 2 while True: loop_key = "%s.%d"%(key,i) if loop_key not in tag_names: tag_names.append(loop_key) tag_values.insert(0,value) tag.name = tag_names tag.value = tag_values tag.save() is_new_tag = False return i+=1 tag = Tag(span_id=span_id,name=names,value=values) tag.save() def put_log(span_id,level,msg,rings = [],**kwargs): ''' ''' log = Log() Span.get_span(span_id) log.span_id = span_id log.event = level log.message = msg log.payload = Span.make_mongo_dict(kwargs) log.save() for ring in rings: Ring(log_id=log.id,name=ring).save() def finish_span(span_id): ''' ''' span = Span.get_span(span_id) span.end_time = datetime.datetime.utcnow() span.save() def start_span(span_id,parent_id=None,tags=[],context=None): ''' ''' span = Span.get_span(span_id) span.start_time = datetime.datetime.utcnow() if parent_id is not None: Span.get_span(parent_id) span.parent_id = parent_id span.save() for k,v in tags: put_tag(span_id,k,v) if context is not None: context['baggage'] = Span.make_mongo_dict(context['baggage']) Context(**context).save() def set_span_name(span_id,name): ''' ''' span = Span.get_span(span_id) span.name = name span.save() class Log(Document): span_id = ObjectIdField(required=True) event = StringField(max_length=20) timestamp = DateTimeField(default=datetime.datetime.utcnow) message = StringField() #这个字段要求必须定义'default'数据库别名 payload = DictField() meta = { 'db_alias':'default', 'indexes':[ { 'fields': ['timestamp'], 'expireAfterSeconds': EXPIRED_SECONDS }] } class Tag(Document): span_id = ObjectIdField(required=True) name = ListField() value = ListField() created_at = DateTimeField(required=True,default=datetime.datetime.utcnow) meta = { 'db_alias':'default', 'indexes':[ COMMON_EXPIRED_INDEX, ] } class Context(Document): span_id = ObjectIdField(required=True) parent_id = ObjectIdField() baggage = DictField() flags = IntField() trace_id = StringField(max_length=100) created_at = DateTimeField(required=True,default=datetime.datetime.utcnow) meta = { 'db_alias':'default', 'indexes':[ COMMON_EXPIRED_INDEX, ] } class Ring(Document): log_id = ObjectIdField(required=True) name = StringField(max_length=20) created_at = DateTimeField(required=True,default=datetime.datetime.utcnow) meta = { 'db_alias':'default', 'indexes':[ COMMON_EXPIRED_INDEX, ] } def obj_to_dict(obj): return dict(obj.to_mongo()) def to_list_dict(objs): lst = [] for obj in objs: lst.append(obj_to_dict(obj)) return lst def full_span_id(span_id): parent_id_list = [str(span_id)] parent_id = span_id while parent_id: span = Span.objects(id=parent_id).first() parent_id = span.parent_id if parent_id: parent_id_list.append(str(parent_id)) parent_id_list.reverse() return ".".join(parent_id_list) def get_span_info(span_id,contain_child=False,to_dict=True): span = Span.get_span(span_id) tags = Tag.objects(span_id=span_id) if to_dict: span_data = obj_to_dict(span) span_data['id'] = full_span_id(span_id) tag_list = to_list_dict(tags) span_data['tags'] = tag_list span_data['childs'] = [] if contain_child: child_spans = Span.objects(parent_id=span_id) childs = [] for child_span in child_spans: childs.append(get_span_info(child_span.id,contain_child,to_dict)) span_data['childs'] = childs context = Context.objects(span_id=span_id).first() if not context: span_data['context'] = None else: span_data['context'] = obj_to_dict(context) return span_data return span def get_span_logs(span_id,timestamp=None,log_ring=None): logs = Log.objects(span_id=span_id) if not logs.first(): return [] if log_ring is not None: ring_logs = [] for log in logs: if Ring.objects(name=log_ring,log_id=log.id).first(): ring_logs.append(log) return ring_logs return to_list_dict(logs) def form_span_id(span_id): obj_span_id = hex(span_id).replace("0x","").replace("L","") return obj_span_id def update_context(context): obj = Context.objects(span_id=context['span_id']).first() obj.baggage = Span.make_mongo_dict(context['baggage']) obj.flags = context['flags'] obj.save() def get_span_context(span_id): context = Context.objects(span_id=span_id).first() if not context: return None return obj_to_dict(context)
AppTrack
/AppTrack-1.0.tar.gz/AppTrack-1.0/apptrack/backend/mongo.py
mongo.py
import json from flask import request, jsonify, Flask, g from collections import OrderedDict import opentracing def lect_request(request, args=None): """ 解析请求参数 request传入参数的header中带有token的字段 :param request: :param args: :return: """ if request.form: lect = request.form.to_dict() elif request.json: lect = copy.deepcopy(request.json) else: try: lect = json.loads(request.data) except: lect = {} if request.args: tmp = request.args.to_dict() lect.update(tmp) if isinstance(args, str): v = lect.get(args, '') return v.encode('utf-8', 'ignore') elif isinstance(args, list): r = [] for k in args: v = lect.get(k, '') r.append(v) return r elif isinstance(args, dict) or isinstance(args, OrderedDict): r = OrderedDict() for k in args: v = lect.get(k, args.get(k, '')) r[k] = v if isinstance(args, OrderedDict): return r.values() else: return dict(r) return lect def create_span(): path = request.path lect = lect_request(request) context = opentracing.global_tracer().extract(opentracing.Format.HTTP_HEADERS,request.headers) if context is not None: g.span = opentracing.global_tracer().start_span(path, opentracing.child_of(context)) else: g.span = opentracing.global_tracer().start_span(path) g.span.set_baggage(lect) g.span.set_tag('path',request.path).set_tag('method',request.method).set_tag('remote_addr',request.remote_addr) g.span.set_tag('url',request.url).set_tag('protocol',request.scheme) def finish_span(response): g.span.set_tag('status_code',response.status_code) #为每个请求注入span id data = response.get_json() data['span_id'] = g.span.span_id error = False if response.status_code == 500: error = True g.span.finish(error=error) response.set_data(json.dumps(data)) return response def init_interceptor(app): app.before_request(create_span) app.after_request(finish_span)
AppTrack
/AppTrack-1.0.tar.gz/AppTrack-1.0/apptrack/web/flask_ability.py
flask_ability.py
import string from App.Validation.Automation.unix import * from App.Validation.Automation.web import * from App.Validation.Automation.purging import * from App.Validation.Automation.alarming import * __version__ = '0.1' class AppValidationAutomation(Unix, Web, Alarming, Purging): """ A Validation Framework to check if your Application is running fine or not.This module can be used for Applications that are built on Unix and have a Web interface. The suite has the capabilty to check Application web urls for accessiblity,and also login into each of those urls to ascertain database connectivity along with sub url accessbility.One can also verfiy processes and mountpoints on the remote hosts which house the application. The password for logging into the web urls is stored in an encrypted file.The Module also has capability to test if Load Balancing and DNS Round Robin is funtioning.High Availabilty Web applications use Load Balancing and DNS Round Robin to add redundancy,high availability, and effective load distribution among the various servers(Web,Application, and Database servers).Further to frontend validations the module provides methods to validate the backend.To carryout backend verification it connects to remote hosts using SSH.Backend verfication involves checking if correct not of processe are running and file systems are accessible.AppValidationAutomation is driven by a tunable configuration file(sample config bundled with this distribution)which is formated in Windows .ini format.Please take a look at the configuration file under cfg/. AppValidationAutomation inherits Web, Unix, Purging and Alarming parent classes and provides a common interface to the user.The user is free to either inherit AppValidationAutomation or the parent classes.AppValidationAutomation does some ground work for the parents. For e.g. read the configuration file and convert the data in the format needed by the parent classes. """ def __init__(self): self.config = {} self.data = {} def validate_urls(self, urls): """ Parses the configuration file and calls Web.validate_url method for each web link.Handles password expiration along with authen -tication failure.On password expiry calls Web.change_web_pwd & Unix.change_unix_pwd to change password both at Web and Unix end. Returns True on success and False on failure.Also notifies via text page and email along with logging the error message. >>> auto_obj = AppValidationAutomation() >>> auto_obj.validate_urls() True """ logger = logging.getLogger(__name__) logging.basicConfig(level=logging.WARN) inaccessible_urls = [] if urls: pass else: logger.error('No url to check accessbility') return False for url in urls: if self.validate_url(url) is False: if re.search(r'Pas.+?Exp',self.data['WEB_MSG']): self.__handle_pwd_expiry(url) elif re.search(r'Auth.+?Fai',self.data['WEB_MSG']): msg = self.data['WEB_MSG'] + "Incorrect credentials...Exiting!" logger.error( msg ) sys.exit(1) elif re.search(r'Missdirected',self.data['WEB_MSG']): msg = url + " : Inaccessible\nERROR: " + \ self.data['WEB_MSG'] logger.error( msg ) inaccessible_urls.append(url) else: logger.info(url + " : OK") if inaccessible_urls: mail_from = self.config['COMMON.MAIL_FROM'] mail_to = self.config['COMMON.MAIL_TO'] smtp = self.config['COMMON.SMTP'] subject = "App Valildation -> Failed" body = "Following links are inaccessible ->\n" body += string.join(inaccessible_urls, "\n") body += "\n Refer logs under" + self.config['COMMON.LOG_DIR'] self.mail(mail_from, mail_to, smtp, subject, body) logger.error(self.data['MAIL_MSG']) mail_from = self.config['COMMON.PAGE_FROM'] mail_to = self.config['COMMON.PAGE_TO'] self.page(mail_from, mail_to, smtp, subject, body) logger.error(self.data['PAGE_MSG']) return False return True def __handle_pwd_expiry(self, url): """Changes password for logging into web url both at unix and web level """ logger = logging.getLogger(__name__) logging.basicConfig(level=logging.WARN) msg = self.data['WEB_MSG'] + " : About to change at Web level :" if self.change_web_pwd(url) is True: logger.info("msg : OK") else : logger.error(msg + self.data['WEB_MSG']); sys.exit(1) msg = "About to change at Unix level :" if self.change_unix_pwd(url) is True: logger.info("msg : OK") else : logger.error(msg + self.data['UNIX_MSG']); sys.exit(1) return True def check_dnsrr_lb(self, url, max_requests=1, min_unique=1): """ Calls Web.dnsrr and Web.lb with parameters read from the configur -ation file.Returns True on success and False on failure.Also notifies via text page and email along with logging the error message. >>> auto_obj = AppValidationAutomation() >>> auto_obj.check_dnsrr_lb() True """ mail_from = self.config['COMMON.MAIL_FROM'] mail_to = self.config['COMMON.MAIL_TO'] smtp = self.config['COMMON.SMTP'] subject = "App Valildation -> Failed" log_dir = self.config['COMMON.LOG_DIR'] logger = logging.getLogger(__name__) fail_flag = False logging.basicConfig(level=logging.WARN) if url: pass else: logger.error('No url supplied to test dnsrr and lb') return False if self.dnsrr(url, max_requests, min_unique) is True: logger.info("DNS Round Robin Validated ") else: fail_flag = True logger.error(url + self.data['WEB_MSG']) body = "DNS Round Robin Validation Failed\n"; body += "\nRefer logs under" + log_dir + "for details" self.mail(mail_from, mail_to, smtp, subject, body) logger.error(self.data['MAIL_MSG']) if self.lb(url, max_requests, min_unique) is True: logger.info("Load balancing Validated ") else: fail_flag = True logger.error(url + self.data['WEB_MSG']) body = "Load Balancing Validation Failed\n"; body += "\nRefer logs under" + log_dir + "for details" self.mail(mail_from, mail_to, smtp, subject, body) logger.error(self.data['MAIL_MSG']) if fail_flag is True: return False else: return True def validate_processes_mountpoints(self, validation_map=None): """ Performs process and mountpoint validation checks.Reads the process and mountpoint related info from the configuration file and calls Unix.validate_process and Unix.validate_mountpoint to do the actual work.True on success and False on failure.Also notifies via text page and email along with logging the error message. >>> auto_obj = AppValidationAutomation() >>> auto_obj.validate_processes_mountpoints() True """ mail_from = self.config['COMMON.MAIL_FROM'] mail_to = self.config['COMMON.MAIL_TO'] smtp = self.config['COMMON.SMTP'] remote_pcmd_tmpl = self.config['COMMON.PROCESS_TMPL'] remote_mcmd_tmpl = self.config['COMMON.FILESYS_TMPL'] logger = logging.getLogger(__name__) logging.basicConfig(level=logging.WARN) faulty_processes, faulty_mountpoints, unavailable_hosts = [], [], [] if validation_map: pass else: logger.error('No remote_host/user/pwd/process/filesys Passed') return False for remote_host in validation_map.keys(): user = validation_map[remote_host]['USER'] passwd = validation_map[remote_host]['PASSWORD'] logger.info("Connecting to " +remote_host+ '...') if self.connect_to(remote_host, user, passwd) is True: logger.info("Connection Successful!") logger.info("Validating Processes...") proc_tmpls = \ validation_map[remote_host]['PROCESSES'].split(',') for proc_tmpl in proc_tmpls: if self.validate_process(proc_tmpl, remote_pcmd_tmpl) is True: logger.info(remote_host+':'+proc_tmpl+':OK') else: logger.error(remote_host+':'+proc_tmpl+':NOT OK:'\ +self.data['UNIX_MSG']) faulty_processes.append(proc_tmpl) logger.info("Validating Mountpoints...") filesystems = \ validation_map[remote_host]['FILE_SYS'].split(',') for fs in filesystems: if self.validate_mountpoint(fs, remote_mcmd_tmpl) is True: logger.info(remote_host+':'+fs+':OK') else: logger.error(remote_host+':'+fs+':NOT OK:'\ +self.data['UNIX_MSG']) faulty_mountpoints.append(fs) else: unavailable_hosts.append(remote_host) if faulty_processes or faulty_mountpoints or unavailable_hosts: subject = "App Validation -> Failed" body = "Unix Validation Failed\n\nRefer logs under" +\ self.config['COMMON.LOG_DIR'] + " for details" self.mail(mail_from, mail_to, smtp, subject, body) logger.info(self.data['MAIL_MSG']) return False return True if __name__ == '__main__': import doctest doctest.testmod()
AppValidationAutomation
/AppValidationAutomation-0%5B1%5D%5B1%5D.1.tar.gz/AppValidationAutomation-0.1/App/Validation/automation.py
automation.py
import os, ssh, re import logging import types import pyDes class Unix: """Bundles utilities to login a remote server and checks if correct no of processes are running and mountpoints are accessible.The remote hosts, processes and mountpoints are stored in configuration file. All member methods return True on success and False on failure.The error message is logged into the log file in case of error. """ def __init__(self): self.config = {} self.data = {} def connect_to(self, remote_host, user, passwd=None): """Connects to remote host passed as an argument,logs in using user and returns True on success.On failure, logs error message and returns False. >>> auto_obj = Unix() >>> auto_obj.connect_to(socket.getfqdn(),"user",passwd="hur") True """ client = ssh.SSHClient() if passwd is None: key_dir = self.config['COMMON.SSH_DIR'] key_files = [key_dir + '/' + key_file for key_file in \ os.listdir(key_dir)] client.set_missing_host_key_policy(ssh.AutoAddPolicy()) logger = logging.getLogger(__name__) try: if passwd is None: client.connect(remote_host, port=22, username=user,\ key_filename=key_files) else: client.connect(remote_host, port=22, username=user,\ password=passwd) except ssh.AuthenticationException, err: logger = logging.getLogger(__name__) logger.error(user+" Unable to login into "+remote_host+ \ "\nERROR:"+str(err)) logger.info("Continuing with the next host...") self.data['UNIX_MSG'] = str(err) return False except ssh.SSHException, err: logger = logging.getLogger(__name__) logger.error(user+" Unable to login into "+remote_host+ \ "\nERROR:"+str(err)) logger.info("Continuing with the next host...") self.data['UNIX_MSG'] = str(err) return False self.data['CONN_STATE'] = client return True def validate_process(self, process_tmpl, remote_pcmd_tmpl): """Validates if process count of a given process is correct(as per process_tmpl passed as an argument.Returns True on sucess and False on Failure. Also logs the error/process count message. >>> auto_obj = Unix() >>> remote_pcmd_tmpl = \ 'ps -eaf | grep -i %s | grep -v grep | wc -l' >>> auto_obj.connect_to(socket.getfqdn(),"user",passwd="hur") True >>> auto_obj.validate_process("ssh:3", remote_pcmd_tmpl) True """ client = self.data['CONN_STATE'] match = re.search(r'(?P<proc>.*)\:(?P<count>.*)$', process_tmpl) process_name = match.group('proc') min_count = match.group('count') remote_cmd = remote_pcmd_tmpl % process_name try: stdin, stdout, stderr = client.exec_command(remote_cmd) except ssh.SSHException, err: logger.error("Unable to fire cmd:"+remote_cmd+ \ "\nERROR:"+str(err)) logger.info("Continuing with the next cmd...") self.data['UNIX_MSG'] = str(err) return False process_count = stdout.readline().strip() process_count = process_count.strip('\n') if stderr.readline(): msg = "Remote Cmd Fired:"+remote_cmd+":Failed\n" msg += "ERROR:"+stderr.readline() self.data['UNIX_MSG'] = msg return False if process_count < min_count: msg = "Remote Cmd Fired:"+remote_cmd+"\n" msg += "Expected "+min_count+" found "+process_count+" running" self.data['UNIX_MSG'] = msg return False return True def validate_mountpoint(self, mountpoint, remote_mcmd_tmpl): """Validate if the mountpoint if presented and accessible.Returns True on success and False on Failure.Logs the error message in case of Failure. >>> auto_obj = Unix() >>> remote_mcmd_tmpl = 'cd %s' >>> auto_obj.connect_to(socket.getfqdn(),"user",passwd="hur") True >>> auto_obj.validate_mountpoint("/export/home/", \ remote_mcmd_tmpl) True """ client = self.data['CONN_STATE'] remote_cmd = remote_mcmd_tmpl % mountpoint try: stdin, stdout, stderr = client.exec_command(remote_cmd) except ssh.SSHException, err: logger.error("Unable to fire cmd:"+remote_cmd+ "\nERROR:"+str(err)) logger.info("Continuing with the next cmd...") self.data['UNIX_MSG'] = str(err) if stderr.readline(): msg = "Remote Cmd Fired:"+remote_cmd+":Failed\n" msg += "ERROR:"+stderr.readline() self.data['UNIX_MSG'] = msg return False return True def change_unix_pwd(self): """Change password at unix level after password expiration at website Level.Uses secret passphrase, old password and new password while changing password.Returns True on success and False on failure.Also, logs the error message incase of failure. """ old_pwd = self.config['COMMON.OLD_PASSWORD'] new_pwd = self.config['COMMON.PASSWORD'] home = self.config['COMMON.DEFAULT_HOME'] enc_pwd_file = self.config['COMMON.ENC_PASS_FILE'] secret_pphrase = self.config['pass_phrase'] if old_pwd == new_pwd: self.data['UNIX_MSG'] = "Password change failed : old pwd = new pwd" return False try: key = pyDes.des(secret_pphrase, pad=None, padmode=PAD_PKCS5) enc_pwd = key.encrypt(new_pwd) enc_file_loc = home + '/' + enc_pwd_file fhandle = open(enc_file_loc, "w") fhandle.write(enc_pwd) except IOError, err: logger.error("Password change failed :ERROR: "+str(err)) return False return True if __name__ == '__main__': import doctest, socket doctest.testmod()
AppValidationAutomation
/AppValidationAutomation-0%5B1%5D%5B1%5D.1.tar.gz/AppValidationAutomation-0.1/App/Validation/Automation/unix.py
unix.py
import sys import re import logging import mechanize from mechanize import ControlNotFoundError, ParseResponse class Web: """Bundles Utilites to check if a weblink is accessible,login into the website if the website has user logon.It also houses utilities to check if DNS Load Balancing and Round Robin functionality is working fine or not.High Availabilty Web applications use Load Balancing and DNS Round Robin to add redundancy,high availability, and effective load distribution among the various servers(Web,Application, and Database servers). """ def __init__(self): self.config = {} self.data = {} def validate_url(self, url): """ Validates if the url passed as argument is accessible or not.logs into the website if the website has user logon page.Returns True on success and False on failure.Logs failure message >>> auto_obj = Web() >>> auto_obj.validate_url("http://docs.python.org") True """ ret_value = True try: br = mechanize.Browser() response = br.open(url) except IOError, err: logger = logging.getLogger(__name__) logger.error(url + "\nERROR: " + str(err)) #logger.debug(br.error()) lookout for an alternative to dump more info print str(err) sys.exit(1) assert br.viewing_html() if 'COMMON.USER' in self.config \ and 'COMMON.PASSWORD' in self.config: if self.config['COMMON.USER'] \ and self.config['COMMON.PASSWORD']: self.data['BROWSER_STATE'] = br ret_value = self.__login() return ret_value def dnsrr(self, url, max_requests, min_unique): """ Validates if the DNS Round Robin functionality is working fine or not.The logic behind this functionality check if to post the url max_requests no of times, login and store the web, application, and DB/Alternate application serve name in a list.The list thus formed (containing combinations of web,app and db/alt. app. directed to max_requests no of times)should contain atleast min_uniqure no of different entries to ascertain that Round Robin is working and web trafic is being distributed evenly.Returns True on success and False on failure.Logs failure message >>> auto_obj = Web() >>> auto_obj.dnsrr("http://docs.python.org", 1, 1) True """ msg = "\nRound Robin details:\n" redirected_uris = [] unique_uris = {} br = mechanize.Browser() for count in range(int(max_requests)): try: response = br.open(url) redirected_uri = br.geturl() msg += url+" Redirected to "+redirected_uri+"\n" redirected_uris.append(redirected_uri) except IOError, err: logger = logging.getLogger(__name__) logger.error(url + "\nERROR : " + str(err)) print str(err) sys.exit(1) for x in redirected_uris: unique_uris[x] = 1 unique = unique_uris.keys() if len(unique) < int(min_unique): self.data['WEB_MSG'] = msg return False else: return True def lb(self, url, max_requests, min_unique): """ Validates if DNS Load balancing functionality is working fine or not.The logic behind this functionality check if to post the url max_requests not of times and store the redirected url in a list. The list thus formed should comprise of atleast min_unique no of different entries to ascertain that Load Balancing is working at the first place and web trafic is being distributed.Returns True on success and False on failure.Logs failure message. >>> auto_obj = Web() >>> auto_obj.config['COMMON.USER'] = None >>> auto_obj.config['COMMON.PASSWORD'] = None >>> auto_obj.lb("http://docs.python.org", 1, 1) True """ msg = "\nLoad Balancing details:\nWeb_Server App_Server Alt_App_Server\n" br = mechanize.Browser() system_info = [] unique_combo = {} for count in range(int(max_requests)): try: response = br.open(url) self.data['BROWSER_STATE'] = br if 'COMMON.USER' in self.config \ and 'COMMON.PASSWORD' in self.config: if self.config['COMMON.USER'] \ and self.config['COMMON.PASSWORD']: self.data['BROWSER_STATE'] = br ret_value = self.__login() if ret_value is True: br = self.data['BROWSER_STATE'] resp = br.response() html_content = resp.read().replace('\n', '') match = \ re.search(r'(strWebSrvrName="(?P<webs>.+?)";)', html_content) web_server = match.group('webs') match = \ re.search(r'(strAppSrvrName="(?P<apps>.+?)";)', html_content) app_server = match.group('apps') match = \ re.search(r'(strKSAppSrvrName="(?P<a_apps>.+?)";)', html_content) alt_app_server = match.group('a_apps') system_info.append(web_server+'_'+app_server+'_'+alt_app_server) else: return False else: return True except IOError, err: logger = logging.getLogger(__name__) logger.error(url + "\nERROR : " + str(err)) print str(err) sys.exit(1) for x in system_info: unique_combo[x] = 1 msg += x+"\n" unique = unique_combo.keys() if len(unique) < int(min_unique): self.data['WEB_MSG'] = msg return False else: return True return True def change_web_pwd(self, url): """ Changes the website password on expiration.The logic used is to post the url and enter credentials into the user logon.Check the the web content of the resulting page for "Password expiry". Proceed with password change if the web content has "Password Expiry".The password generated contains three letters from the next month followed by a dash '-' and 3 digit random no.Returns True on success and False on failure.Logs failure message. >>> auto_obj = Web() >>> auto_obj.change_web_pwd("http://docs.python.org") True """ return True def __login(self): """ Private member method to login into the website using login details stored in configuration file.Returns True on success and False on failure.Logs failure message. """ #Reinstate browser state br = self.data['BROWSER_STATE'] #select form with user and password field br.select_form(predicate=self.__form_with_fields("user", "password")) br['user'] = self.config['COMMON.USER'] br['password'] = self.config['COMMON.PASSWORD'] #update site and zone if specified in config file if 'COMMON.SITE' in self.config and 'COMMON.ZONE' in self.config: try: br.form.set_all_readonly(False) br.form["shortsite"] = self.config['COMMON.SITE'] zone1 = br.form.find_control("zone") mechanize.Item(zone1, {"contents": \ "lee10","value": "lee10"}) br.form["zone"] = ["lee10"] except ControlNotFoundError, err: logger = logging.getLogger(__name__) logger.info(str(err)) try: request = br.click() response = mechanize.urlopen(request) except IOError, err: logger = logging.getLogger(__name__) logger.error(str(err)) logger.debug(response.info()) print str(err) sys.exit(1) assert br.viewing_html() html_content = response.read().replace('\n', '') if re.search(r'Password\s+has\s+expired', html_content): self.data['WEB_MSG'] = "Password has Expired" self.data['BROWSER_STATE'] = br return False elif re.search(r'Authentication\s+Failure', html_content): self.data['WEB_MSG'] = "Authentication Failure!" return False elif re.search(r'launchMenu\((.*)\)\;', html_content): string = re.search(r'launchMenu\((.*)\)\;', html_content) request_string = string.group(1) (web_server, web_server_ip, web_port, app_server, user, \ menu_tokens, auto_tokens, site, zone, slif_flag) \ = re.split(r'\W+,\W+', request_string) web_server = re.sub(r'^\'', '', web_server) slif_flag = re.sub(r'\'$', '', slif_flag) menu_url = 'http://' + web_server_ip + ':' + web_port menu_url += '/LoginIWS_Servlet/Menu?webserver=' + web_server menu_url += '&webport=' + web_port + '&appserver=' + app_server menu_url += '&user=' + user + '&menuTokens=' + menu_tokens menu_url += '&autoTokens=' + auto_tokens + '&site=' + site menu_url += '&zone=' + zone + '&SLIflag=' + slif_flag menu_url += '&code=' + 'x9y8z70D0' try: response = br.open(menu_url) except IOError, err: logger = logging.getLogger(__name__) logger.error(str(err)) logger.debug(response.info()) return False self.data['BROWSER_STATE'] = br return True else: self.data['WEB_MSG'] = "Missdirected " + response.geturl() return False def __form_with_fields(self, *fields): """ Generator of form predicate functions. """ def __pred(form): for field_name in fields: try: form.find_control(field_name) except ControlNotFoundError, err: logger = logging.getLogger(__name__) #logger.error(str(err)) return False return True return __pred if __name__ == '__main__': import doctest doctest.testmod()
AppValidationAutomation
/AppValidationAutomation-0%5B1%5D%5B1%5D.1.tar.gz/AppValidationAutomation-0.1/App/Validation/Automation/web.py
web.py
import smtplib import logging class Alarming: """ Notifies of a potential issue via email and/or text message.The recipient(s) address is a part of the configuration file. """ def __init__(self): self.config = {} self.data = {} def mail(self, mail_from, mail_to, smtp, subject, body): """ Sends email notification about the exception encountered while performing validation. >>> auto_obj = Alarming() >>> hostname = socket.getfqdn() >>> user = os.environ['USER'] >>> mail_from = user+'@'+hostname >>> mail_to = user+'@'+hostname >>> auto_obj.mail(mail_from, mail_to, hostname, "test", "test") True """ try: server = smtplib.SMTP(smtp) server.sendmail(mail_from, mail_to, body) server.quit() except smtplib.SMTPException, err: logger = logging.getLogger(__name__) logger.error("Email sending failed :ERROR:"+str(err)+"\n") self.data['MAIL_MSG'] = str(err) return False self.data['MAIL_MSG'] \ = "\nMail sent to "+mail_to+" with content:\n"+body+"\n" return True def page(self, mail_from, mail_to, smtp, subject, body): """ Sends page notification about the exception encountered while performing validation. >>> auto_obj = Alarming() >>> hostname = socket.getfqdn() >>> user = os.environ['USER'] >>> mail_from = user+'@'+hostname >>> mail_to = user+'@'+hostname >>> auto_obj.page(mail_from, mail_to, hostname, "test", "test") True """ try: server = smtplib.SMTP(smtp) server.sendmail(mail_from, mail_to, body) server.quit() except smtplib.SMTPException, err: logger = logging.getLogger(__name__) logger.error("Page sending failed :ERROR:"+str(err)+"\n") self.data['PAGE_MSG'] = str(err) return False self.data['PAGE_MSG'] = "\nPage sent to "+mail_to+" with the\ following content:\n"+body+"\n" return True if __name__ == '__main__': import doctest, socket, os doctest.testmod()
AppValidationAutomation
/AppValidationAutomation-0%5B1%5D%5B1%5D.1.tar.gz/AppValidationAutomation-0.1/App/Validation/Automation/alarming.py
alarming.py
The README file helps one on the Generation of SSH Public/Private Keys and How to use the config file. How to generate Public/Private key pairs for SSH: The utility ssh-keygen is used to generate that Public/Private key pair: user@localhost>ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/user/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/user/.ssh/id_rsa. Your public key has been saved in /home/user/.ssh/id_rsa.pub. The key fingerprint is: f6:61:a8:27:35:cf:4c:6d:13:22:70:cf:4c:c8:a0:23 The command ssh-keygen -t rsa initiated the creation of the key pair.Adding a passphrase is not required so just press enter.The private key gets saved in .ssh/id_rsa. This file is read-only and only for you. No one else must see the content of that file, as it is used to decrypt all correspondence encrypted with the public key. The public key gets stored in .ssh/id_rsa.pub.The content of the id_rsa.pub needs to be copied in the file .ssh/authorized_keys of the system you wish to SSH to without being prompted for a password. Here are the steps: Create .ssh dir on remote host(The dir may already exist,No issues): user@localhost>ssh user@remotehost mkdir -p .ssh user@remotehost's password: Append user's new public key to user@remotehost : .ssh/authorized_keys and enter user's password: user@localhost>cat .ssh/id_rsa.pub | ssh user@remotehost 'cat >> .ssh/authorized_keys' user@remotehost's password: Test login without password: user@localhost>ssh user@remotehost user@remotehost>hostname remotehost How to Use configuration file: AppValidationAutomation is driven by a tunable configuration file.The configuration file is in Windows .ini format.The wrapper script using App::Validation::Automation needs to either read the configuration file or build the configuration itself.The configuration file is broadly divided into two parts COMMON and Remote host specific.The COMMON part contains generic info used by AppValidationAutomation not specific to any host. Example: [COMMON] #User to login into Web links USER = web_user #Common User to login into remote host REMOTE_USER = user #Post link MAX_REQ no of times, used while testing Load #Balancing and DNS round robin functionality MAX_REQ = 10 #Minimum distinct redirected uris to ascertain Load Balancing #and DNS round robin is working fine MIN_UNQ = 2 #Log file extension LOG_EXTN = log #Print SSH debugging info to STDOUT DEBUG_SSH = 1 #Try SSH2 protocol first and then SSH1 SSH_PROTO = '2,1' #Private keys for each server(AA,KA...) used for SSH ID_RSA = /home/user/.ssh/id_rsa_AA,/home/user/.ssh/id_rsa_KA MAIL_TO = '[email protected],[email protected]' PAGE_TO = '[email protected]' FROM = [email protected] SMTP = localhost.com #Text file containing Encrypted password for USER ENC_PASS_FILE = pass.txt DEFAULT_HOME = /home/App/Validation LOG_DIR = /home/App/Validation/log #Log file retention period, delete log file older than 5 days RET_PERIOD = 5 #Main Weblink used for Load Balancing and DNS round robin test LINK = http://cpan.org #Remote command fired to get process count.%s is replaced process name PROCESS_TMPL = ps -eaf | grep -i %s | grep -v grep | wc -l #Remote command fired to check filesystem.%s is replaced by filesystem name FILESYS_TMPL = cd %s #FQDN of remote server [AA.xyz.com] #Processes to verify on remote hosts along with their minimum quantity PROCESSES = BBL:1, EPsrv:1, WEBLEPsrv:1 #Filesystems to verify on remote hosts FILE_SYS = /test, /export/home #FQDN of remote server [KA.xyz.com] #Processes to verify on remote hosts along with their minimum quantity PROCESSES = BBL:1, EPsrv:1, WEBLEPsrv:1 #Filesystems to verify on remote hosts FILE_SYS = /test, /export/home #Links specific to KA server these links are checked for accessibility LINKS = http://KA.xyz.com:7000,http://KA.xyz.com:7100
AppValidationAutomation
/AppValidationAutomation-0%5B1%5D%5B1%5D.1.tar.gz/AppValidationAutomation-0.1/docs/README.txt
README.txt
import os import re import sys import getopt import logging import profile from types import * from pyDes import * from datetime import date, datetime, time from ConfigParser import * from App.Validation.automation import AppValidationAutomation class AutoWrapper(AppValidationAutomation): def __init__(self): self.config = {} self.data = {} def parse_cmdline(self): """Parse and store command line options and values""" try: opts, args = getopt.getopt( sys.argv[1:], "hc:p:f", ["help", "config=", "passphrase=", "forcerun"]) except getopt.GetoptError, err: print str(err) self.display_usage() sys.exit(2) if len(opts) == 0: print "No cmd line args specified" self.display_usage() print "Exiting..." sys.exit(1) for o, a in opts: if o in ("-h", "--help"): self.display_usage() sys.exit() elif o in ("-c", "--config"): self.config['config_file'] = a elif o in ("-p", "--passphrase"): self.config['pass_phrase'] = a elif o in ("-f", "--forcerun"): self.config['forced_run'] = True else: assert False, "Unhandled Option" return True def store_config(self): """Parse and store configuration file in self.config""" try: config = ConfigParser() config.read(self.config['config_file']) if len(config.sections()) < 1: print "Config file missing min. data to proceed.Exiting..." sys.exit(1) for section in config.sections(): for kv_pair in config.items(section): key = section + '.' + kv_pair[0].upper() self.config[key] = kv_pair[1] #Read encrypted stored in config file pass_file \ = self.config['COMMON.DEFAULT_HOME'] + '/' + self.config['COMMON.ENC_PASS_FILE'] fhandle = open(pass_file) encrypted_password = fhandle.read() self.config['COMMON.PASSWORD'] \ = self.__decrypt_password(encrypted_password) except ParsingError, err: print "Exception in parsing config file...Exiting!",str(err) sys.exit(1) except NoSectionError, err: print "Section missing.Cannot proceed further...Exiting!",str(err) sys.exit(1) except IOError, err: print "Unable to read pass_file ...Exiting!",str(err) sys.exit(1) return self.config # for testing def create_logfile(self): """Creates Log file""" log_dir = self.config['COMMON.LOG_DIR'] + '/' date_stamp = date.today() log_extn = '.' + self.config['COMMON.LOG_EXTN'] log_file = log_dir + os.path.basename(sys.argv[0]) + \ str(date_stamp) + log_extn log_level = self.config['COMMON.LOG_LEVEL'] logging.basicConfig(filename=log_file,level=logging.INFO) return True def chk_mtce_on(self): """Check if in a Maintenance window""" mtce_window = self.config['COMMON.MTCE_WINDOW'] day_map = {1:'Mon', 2:'Tue', 3:'Wed', 4:'Thu', 5:'Fri', 6:'Sat', 7:'Sun'} mtce_day, mtce_time = mtce_window.split() mtce_start, mtce_end = mtce_time.split('-') mtce_start, mtce_end = int(mtce_start), int(mtce_end) #Look out for a better way time_stamp = str(datetime.now()).split()[1:] hour, min, sec = time_stamp[0].split(':', 2) time_now = int(hour + min) year, month, day = str(date.today()).split('-') day = date(int(year), int(month), int(day)).isoweekday() day = day_map[day] if day == mtce_day and (hour >= mtce_start and hour <= mtce_end): return True else: return False def display_usage(self): """Print Script's Usage""" use = "Script run with incorrect parameters.Usage:\n " use += " %r -c <path_to_configfile> -p <passphrase> -f \n OR \n" use += " %r --config <path_to_configfile> --passphrase <pssphrase> --forcerun" print use % (sys.argv[0], sys.argv[0]) def __decrypt_password(self, encrypted_password): """Decrypt Password""" key = des(self.config['pass_phrase'], pad=None, padmode=PAD_PKCS5) return key.decrypt(encrypted_password) if __name__ == "__main__": auto_obj = AutoWrapper() logger = logging.getLogger(__name__) #profile.Profile.bias = 2.5e-06 #ret_value = profile.run('auto_obj.parse_cmdline()') #ret_value = profile.run('auto_obj.store_config()') #ret_value = profile.run('auto_obj.create_logfile()') #ret_value = profile.run('auto_obj.purge()') #ret_value = profile.run('auto_obj.validate_urls()') #ret_value = profile.run('auto_obj.check_dnsrr_lb()') ret_value = auto_obj.parse_cmdline() ret_value = auto_obj.store_config() ret_value = auto_obj.create_logfile() #prepare ground for log file purging log_dir = auto_obj.config['COMMON.LOG_DIR'] log_extn = auto_obj.config['COMMON.LOG_EXTN'] log_ret_period = int(auto_obj.config['COMMON.RET_PERIOD']) * 24 * 3600 ret_value = auto_obj.purge(log_dir, log_ret_period, log_extn) #Prepare ground for url validation,dns round robin,load #balancing,process and mountpoint validation only_urls = re.compile(r'LINKS') only_processes = re.compile(r'PROCESSES') validation_map = {} urls = [] url = auto_obj.config['COMMON.LINK'] max_requests = int(auto_obj.config['COMMON.MAX_REQ']) min_unique = int(auto_obj.config['COMMON.MIN_UNQ']) if 'COMMON.REMOTE_USER' in auto_obj.config \ and auto_obj.config['COMMON.REMOTE_USER'] is not None: user = auto_obj.config['COMMON.REMOTE_USER'] else: user = os.environ['USER'] for key in auto_obj.config.keys(): if only_processes.search(key): match = re.search(r'(?P<host>.*)\..*$', key) hostname = match.group('host') mount_key = hostname+'.FILE_SYS' validation_map[hostname] = \ {'USER': user, 'PASSWORD': None, \ 'PROCESSES': auto_obj.config[key], \ 'FILE_SYS': auto_obj.config[mount_key]} if only_urls.search(key): ws_urls = auto_obj.config[key].split(',') [urls.append(ws_url) for ws_url in ws_urls] ret_value = auto_obj.validate_urls(urls) ret_value = auto_obj.check_dnsrr_lb(url, max_requests, min_unique) ret_value = \ auto_obj.validate_processes_mountpoints(validation_map) if auto_obj.chk_mtce_on() is True and 'forced_run' not in auto_obj.config: msg = "Maintenance is on - " + auto_obj.config['COMMON.MTCE_WINDOW'] msg += " Cannot proceed.To run in maintenance use forcerun cmd switch" logger.info(msg) print msg auto_obj.display_usage() sys.exit(1)
AppValidationAutomation
/AppValidationAutomation-0%5B1%5D%5B1%5D.1.tar.gz/AppValidationAutomation-0.1/bin/app_validation.py
app_validation.py
import ast import json import os import pathlib from enum import Enum import requests class Status(str, Enum): Complete = "Complete" Processing = "Processing" Failed = "Failed" Canceled = "Canceled" Scheduled = "Scheduled" Paused = "Paused" class AppWrapper: def __init__(self): try: self.tenant_id = os.getenv("TENANT_ID") self.TOAD_HOST = os.getenv("TOAD_HOST", None) self.task_id = os.environ["TASK_ID"] self.main_app_id = os.environ["MAIN_APP_ID"] self.file_folder = os.environ["POD_FILE_PATH"] self.app_input_files = ast.literal_eval( os.environ["APP_INPUT_FILES"] ) if len(self.app_input_files) != 0: self.download_file_from_s3() except Exception as e: error_log = f"Initialization Failed: {str(e)}" self.update_status(Status.Failed.value, error_log) def download_file_from_s3(self): for index, s3_path in enumerate(self.app_input_files): file_key = s3_path.split("/")[2] presigned_get_url = requests.get( f"{self.TOAD_HOST}/utils/presigned-download-url/?app_id={self.main_app_id}&task_id={self.task_id}&file_name={file_key}" ).json()["url"] res = requests.get(presigned_get_url) if res.status_code != 200: error_log = f"Failed: File download. \ status code: {res.status_code} detail: {res.reason} \ file_key: {file_key} presigned url: {presigned_get_url}" self.update_status(Status.Failed.value, error_log) file_path = os.path.join(self.file_folder, file_key) pathlib.Path(file_path).parents[0].mkdir( parents=True, exist_ok=True ) with open(file_path, "wb") as f: f.write(res.content) def upload_file_to_s3(self, result): file_path = result["file_path"] file_name = file_path.split("/")[-1] presigned_put_url = requests.get( f"{self.TOAD_HOST}/utils/presigned-upload-url/?app_id={self.main_app_id}&task_id={self.task_id}&file_name={file_name}" ).json()["url"] with open(file_path, "rb") as file: res = requests.put(presigned_put_url, data=file) if res.status_code != 200: error_log = f"Failed: File upload. \ status code: {res.status_code} detail: {res.reason} \ file_key: {file_name} presigned url: {presigned_put_url}" self.update_status(Status.Failed.value, error_log) def update_status(self, status: Status, log: str): print(f"[INFO] {log}") requests.put( f"{self.TOAD_HOST}/tasks/{self.task_id}/status/{status}/log/", data=json.dumps({"log": f"[AppWrapper] - {log}"}), ) if status == "Failed": exit() def validate_result_format(self, result: dict): if not isinstance(result, dict) or "type" not in result: error_log = "App result should include 'type' key" self.update_status(Status.Failed.value, error_log) if result["type"] == "link" and "url" not in result: error_log = "App result should include 'url' key for link type" self.update_status(Status.Failed.value, error_log) if result["type"] == "download" and "file_path" not in result: error_log = ( "App result should include 'file_path' key for download type" ) self.update_status(Status.Failed.value, error_log) def __call__(self, func): def inner(*args, **kwargs): try: result = func(*args, **kwargs) except Exception as e: # print(traceback.print_exc()) error_log = f"App failed: {e}" self.update_status(Status.Failed.value, error_log) try: self.validate_result_format(result) if result["type"] == "download": self.upload_file_to_s3(result) data = {"task_id": self.task_id, "result": result} requests.post( f"{self.TOAD_HOST}/output/", data=json.dumps(data) ) self.update_status(Status.Complete.value, log="App completed") except Exception as e: error_log = f"Post app failed: {e}" self.update_status(Status.Failed.value, error_log) return inner
AppWrapper
/AppWrapper-0.1.7-py3-none-any.whl/app_wrapper/app_wrapper.py
app_wrapper.py
import json import os import ast import requests import pathlib def wrapper(): def decorator(func): def app_wrapper(*args, **kwargs): try: TOAD_HOST = os.getenv("TOAD_HOST", None) task_id = os.environ["TASK_ID"] main_app_id = os.environ["MAIN_APP_ID"] file_folder = os.environ["POD_FILE_PATH"] app_input_files = ast.literal_eval( os.environ["APP_INPUT_FILES"] ) except Exception as e: error_type = type(e).__name__ error_log = ( f"[Pod] AppWrapper - Failed: {error_type} - {str(e)}" ) print(f"[AppWrapper] {error_log}") requests.put( f"{TOAD_HOST}/tasks/{task_id}/status/Failed/log/", data=json.dumps({"log": f"AppWrapper - {error_log}"}), ) exit() # input file이 있는 경우 if len(app_input_files) != 0: for index, s3_path in enumerate(app_input_files): file_key = s3_path.split("/")[2] presigned_get_url = requests.get( f"{TOAD_HOST}/utils/presigned-download-url/?app_id={main_app_id}&task_id={task_id}&file_name={file_key}" ).json()["url"] res = requests.get(presigned_get_url) if res.status_code != 200: error_log = f"[Pod] AppWrapper - Failed: File download. \ status code: {res.status_code} detail: {res.reason} \ file_key: {file_key} presigned url: {presigned_get_url}" print(error_log) requests.put( f"{TOAD_HOST}/tasks/{task_id}/status/Failed/log/", data=json.dumps( {"log": f"AppWrapper - {error_log}"} ), ) exit() file_path = os.path.join(file_folder, file_key) pathlib.Path(file_path).parents[0].mkdir( parents=True, exist_ok=True ) with open(file_path, "wb") as f: f.write(res.content) excluded_keys = ["email", "password"] excluded_values = [os.environ["ACCESS_KEY"]] print("[Input Infomation]") for key, value in kwargs.items(): if key not in excluded_keys and value not in excluded_values: print(f"{key}={value}") print("") try: result = func(*args, **kwargs) except Exception as e: print(e) requests.put( f"{TOAD_HOST}/tasks/{task_id}/status/Failed/log/", data=json.dumps({"log": f"Pod - Job failed: {e}"}), ) exit() try: # result의 type result_type = result["type"] # app의 output에 파일있는 경우 if result_type == "download": file_path = result["file_path"] file_name = file_path.split("/")[-1] # file put하기 위한 url 요청 presigned_put_url = requests.get( f"{TOAD_HOST}/utils/presigned-upload-url/?app_id={main_app_id}&task_id={task_id}&file_name={file_name}" ).json()["url"] with open(file_path, "rb") as file: res = requests.put(presigned_put_url, data=file) if res.status_code != 200: error_log = f"[Pod] AppWrapper - Failed: File upload. \ status code: {res.status_code} detail: {res.reason} \ file_key: {file_key} presigned url: {presigned_put_url}" print(error_log) requests.put( f"{TOAD_HOST}/tasks/{task_id}/status/Failed/log/", data=json.dumps( {"log": f"AppWrapper - {error_log}"} ), ) exit() # function의 result 전달 data = {"task_id": task_id, "result": result} requests.post(f"{TOAD_HOST}/output/", data=json.dumps(data)) requests.put( f"{TOAD_HOST}/tasks/{task_id}/status/Complete/log/", data=json.dumps({"log": "Pod - Job completed"}), ) except Exception as e: error_log = f"AppWrapper - Post app failed: {e}" requests.put( f"{TOAD_HOST}/tasks/{task_id}/status/Failed/log/", data=json.dumps({"log": error_log}), ) print(error_log) exit() return app_wrapper return decorator
AppWrapper
/AppWrapper-0.1.7-py3-none-any.whl/app_common/app_common.py
app_common.py
<h1 align = "center">:rocket: App :facepunch:</h1> --- ## Install ```bash pip install -U appzoo ``` ## Usage - Rest Api ```python import jieba from iapp import App pred1 = lambda **kwargs: kwargs['x'] + kwargs['y'] pred2 = lambda x=1, y=1: x - y pred3 = lambda text='小米是家不错的公司': jieba.lcut(text) app = App(verbose=True) app.add_route("/", pred1, result_key='result') app.add_route("/f1", pred1, version="1") app.add_route("/f2", pred2, version="2") app.add_route("/f3", pred3, version="3") app.run() ``` - Scheduler ```python from iapp.scheduler import Scheduler def task1(x): print(x) import logging import time logging.warning(f'Task1: {time.ctime()}') def task2(): import logging import time logging.warning(f'Task2: {time.ctime()}') def task3(): return 1 / 0 def my_listener(event): if event.exception: print(event.traceback) print('任务出错了!!!!!!') else: print('任务照常运行...') scheduler = Scheduler() scheduler.add_job(task1, 'interval', seconds=3, args=('定时任务',)) scheduler.add_job(task2, 'interval', seconds=5) scheduler.add_job(task3, 'interval', seconds=1) scheduler.add_listener(my_listener) scheduler.start() while 1: pass ``` --- # TODO - add logger
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/README_.md
README_.md
[![Downloads](http://pepy.tech/badge/AppZoo)](http://pepy.tech/project/AppZoo) [![Open in Streamlit](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://share.streamlit.io/jie-yuan/appzoo/apps_streamlit/demo.py) <h1 align = "center">:rocket: AppZoo :facepunch:</h1> --- ## Install ```bash pip install -U appzoo ``` ## Usage - Rest Api ```python import jieba from appzoo import App pred1 = lambda **kwargs: kwargs['x'] + kwargs['y'] pred2 = lambda x=1, y=1: x - y pred3 = lambda text='小米是家不错的公司': jieba.lcut(text) app = App(verbose=True) app.add_route("/", pred1, result_key='result') app.add_route("/f1", pred1, version="1") app.add_route("/f2", pred2, version="2") app.add_route("/f3", pred3, version="3") app.run() # appcli easy-run ./apps ``` - 带缓存 ```python @lru_cache() def post_func(kwargs: str): logger.info(kwargs) return kwargs app.add_route_plus(post_func) ``` - Fast Api ```bash app-run - fastapi demo.py app-run - fastapi -- --help ``` - [Streamlit App](https://share.streamlit.io/jie-yuan/appzoo/apps_streamlit/demo.py) ```bash app-run - streamlit demo.py app-run - streamlit -- --help ``` --- ## TODO - add logger: 采样 - add scheduler - add 监听服务 - add rpc服务 - hive等穿透 - add thrift https://github.com/Thriftpy/thriftpy2 - add dataReport - add plotly - add explain - add 限制次数 https://slowapi.readthedocs.io/en/latest/ --- 对于RESTful API的URL具体设计的规范如下: 1.不用大写字母,所有单词使用英文且小写。 2.连字符用中杠"-“而不用下杠”_" 3.正确使用 “/“表示层级关系,URL的层级不要过深,并且越靠前的层级应该相对越稳定 4.结尾不要包含正斜杠分隔符”/” 5.URL中不出现动词,用请求方式表示动作 6.资源表示用复数不要用单数 7.不要使用文件扩展名 --- [FastAPI--依赖注入之Depends](https://blog.csdn.net/shykevin/article/details/106834526)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/README.md
README.md
from io import BytesIO from starlette.status import * from starlette.responses import * from starlette.staticfiles import StaticFiles from fastapi import FastAPI, Form, Depends, File, UploadFile, Body, Request, BackgroundTasks # ME from meutils.pipe import * from meutils.str_utils import json_loads # logger.add('runtime_{time}.log') class App(object): """ from appzoo import App app = App() app_ = app.app app.add_route() if __name__ == '__main__': app.run(app.app_from(__file__), port=9955, debug=True) """ def __init__(self, config_init=None, **kwargs): self.app = FastAPI(**kwargs) # 原生接口 self.get = self.app.get self.post = self.app.post self.api_route = self.app.api_route self.mount = self.app.mount # mount('/subapi', subapp) # 增加配置项,方便热更新 self.config = get_config(config_init) # 全局变量 # 功能性接口 self.add_route_plus(self.app_config, methods=["GET", "POST"]) self.add_route_plus(self.proxy_app, methods="POST") # 代理服务,自己调自己有问题 def run(self, app=None, host="0.0.0.0", port=8000, workers=1, access_log=True, debug=False, **kwargs): """ :param app: app字符串可开启热更新 debug/reload :param host: :param port: :param workers: :param access_log: :param debug: reload :param kwargs: :return: """ import uvicorn """ https://www.cnblogs.com/poloyy/p/15549265.html https://blog.csdn.net/qq_33801641/article/details/121313494 """ # _ = uvicorn.Config( # app if app else self.app, # host=host, port=port, workers=workers, access_log=access_log, debug=debug, **kwargs # ) # server = uvicorn.Server(_) # from appzoo.utils.settings import uvicorn_logger_init # uvicorn_logger_init() # server.run() # uvicorn.config.LOGGING_CONFIG['formatters']['access']['fmt'] = f""" # 🔥 %(asctime)s | {LOCAL_HOST} - %(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s # """.strip() uvicorn.config.LOGGING_CONFIG['formatters']['access']['fmt'] = f""" 🔥 %(asctime)s - %(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s """.strip() uvicorn.run( app if app else self.app, host=host, port=port, workers=workers, access_log=access_log, debug=debug, **kwargs ) def gunicorn_run(self, main_app='main:app_', gunicorn_conf=None): if gunicorn_conf is None: gunicorn_conf = get_resolve_path('gunicorn.conf.py', __file__) assert Path(gunicorn_conf).exists() os.system(f"gunicorn -c {gunicorn_conf} {main_app}") def add_route(self, path='/xxx', func=lambda x='demo': x, method="GET", **kwargs): handler = self._handler(func, method, **kwargs) self.app.api_route(path=path, methods=[method])(handler) def add_route_plus(self, func, path=None, methods: Union[List, str] = "GET", **kwargs): """ :param path: :param func: @lru_cache() def cache(kwargs: str): time.sleep(3) return kwargs # json.load(kwargs.replace("'", '"')) def nocache(kwargs: dict): # 不指定类型默认字典输入 time.sleep(3) return kwargs :param method: :param kwargs: :return: """ assert isinstance(func, Callable) if isinstance(methods, str): methods = [methods] if path is None: path = f"""/{func.__name__.replace('_', '-')}""" # todo 前缀 assert path.startswith('/') handler = self._handler_plus(func, **kwargs) self.app.api_route(path=path, methods=methods)(handler) # method def add_route_uploadfiles(self, path='/xxx', func=lambda x='demo': x, **kwargs): """ def read_func(**kwargs): logger.info(kwargs) return pd.read_csv(kwargs['files'][0], names=['word']).to_dict('r') app.add_route_uploadfiles('/upload', read_func) """ handler = self._handler4files(func, **kwargs) self.app.api_route(path=path, methods=['POST'])(handler) # method def add_apps(self, app_dir='apps', main_func='main', **kwargs): # todo: 优化 """加载当前app_dir文件夹下的所有app(递归), 入口函数都是main 1. 过滤掉 _ 开头的py文件 2. 支持单文件 appcli easy-run <app_dir> """ app_home = Path(sys_path_append(app_dir)) n = app_home.parts.__len__() pattern = Path(app_dir).name if Path(app_dir).is_file() else '*.py' routes = [] for p in app_home.rglob(pattern): home_parts = p.parts[n:] route = f'/{app_home.stem}/' + "/".join(home_parts)[:-3] module = importlib.import_module('.'.join(home_parts)[:-3]) if hasattr(module, main_func): func = getattr(module, main_func) self.add_route(route, func, method='POST', **kwargs) routes.append(route) else: logger.warning(f"Filter: {p}") logger.info(f"Add Routes: {routes}") self.add_route(f'/__{app_home.stem}', lambda: routes, method='GET', **kwargs) return routes def _handler(self, func, method='GET', result_key='data', **kwargs): """ :param func: :param method: get -> request: Request post -> kwargs: dict :param result_key: :return: """ if method == 'GET': async def handler(request: Request): input = request.query_params._dict return self._try_func(input, func, result_key, **kwargs) elif method == 'POST': async def handler(kwargs_: dict): input = kwargs_ return self._try_func(input, func, result_key, **kwargs) else: async def handler(): return {'Warning': 'method not in {"GET", "POST"}'} return handler def _handler4files(self, func, **kwargs): async def handler(request: Request, files: List[UploadFile] = File(...)): input = request.query_params._dict # input['files'] = [BytesIO(await file.read()) for file in files] for file in files: bio = BytesIO(await file.read()) bio.name = file.filename input.setdefault('files', []).append(bio) return self._try_func_plus(input, func, **kwargs) return handler def _handler_plus(self, func, **kwargs): # todo 兼容所有类型 async def handler(request: Request): input = request.query_params._dict body = await request.body() if body.startswith(b'{'): # 主要分支 # json={} input.update(json_loads(body)) elif request.method == 'POST' and 'multipart/form-data' in request.headers.get("Content-Type"): # files={'files': open('xx')} form = await request.form() # 重复 await for file in form.getlist('files'): # files bio = BytesIO(await file.read()) bio.name = file.filename input.setdefault('files', []).append(bio) elif body: # data:dict => application/x-www-form-urlencoded input.update({'__data__': body}) # 非 json 请求体 # input4str 方便 cache if 'str' in str(func.__annotations__): # todo: cache可支持dict 取消判断 input = str(input) # json.loads elif 'tuple' in str(func.__annotations__): input = tuple(input.items()) # dict return self._try_func_plus(input, func, **kwargs) return handler @staticmethod def _try_func(input, func, result_key='data', **kwargs): # todo: 可否用装饰器 __debug = input.pop('__debug', 0) output = OrderedDict() output['error_code'] = 0 output['error_msg'] = "SUCCESS" if __debug: output['requestParams'] = input output['timestamp'] = time.ctime() try: output[result_key] = func(**input) except Exception as error: output['error_code'] = 1 # 通用错误 output['error_msg'] = traceback.format_exc().strip() if __debug else error # debug状态获取详细信息 finally: output.update(kwargs) return output @staticmethod def _try_func_plus(input, func, **kwargs): output = OrderedDict(code=0, msg="SUCCESS", **kwargs) try: output['data'] = func(input) except Exception as error: output['code'] = 1 # 通用错误 output['data'] = kwargs.get('data') output['msg'] = traceback.format_exc().strip().split('\n') \ if output['data'] is None else error # 无默认值则获取详细信息 logger.error(output['msg']) return output def app_from(self, file=__file__, app='app_'): return f"{Path(file).stem}:{app}" def app_config(self, kwargs: str): _ = json_loads(kwargs) if _ and _ != self.config: # 更新配置 self.config.update(_) logger.warning("Configuration item is modified !!!") return self.config def proxy_app(self, kwargs: dict): """代理层 { "url": "http://0.0.0.0:8000/xx", "method": "post", "json": {"a": 1} } """ r = requests.request(**kwargs) return r.json() if __name__ == '__main__': import uvicorn app = App() app_ = app.app app.add_route('/get', lambda **kwargs: kwargs, method="GET", result_key="GetResult") app.add_route('/post', lambda **kwargs: kwargs, method="POST", result_key="PostResult") app.run(port=9000, debug=False, reload=False, access_log=True) # app.run(f"{app.app_from(__file__)}", port=9000, debug=False, reload=False) # app_的在 __main__ 之上
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/app.py
app.py
import asyncio import inspect import logging import traceback from datetime import datetime, time, timedelta from typing import Callable, Optional, Union __all__ = ('task', 'SanicScheduler', 'make_task') logger = logging.getLogger('scheduler') _tasks = {} _wrk = [] def make_task(fn: Callable, period: Optional[timedelta] = None, start: Optional[Union[timedelta, time]] = None) -> None: """Make task.""" _tasks[fn] = Task(fn, period, start) def task(period: Optional[timedelta] = None, start: Optional[Union[timedelta, time]] = None): """Decorate the function to run on schedule.""" def wrapper(fn): make_task(fn, period, start) return fn return wrapper class SanicScheduler: def __init__(self, app=None, utc=True): self.app = app if app: self.init_app(app, utc) def init_app(self, app, utc=True): self.app = app @app.listener("after_server_start") async def run_scheduler(_app, loop): for i in _tasks.values(): _wrk.append(loop.create_task(i.run(_app, utc))) @app.listener("before_server_stop") async def stop_scheduler(_app, _): for i in _wrk: i.cancel() return self @classmethod def task_info(cls): return _tasks class Task: def __init__(self, func: Callable, period: Optional[timedelta], start: Optional[Union[timedelta, time]]): self.func = func self.func_name = func.__name__ self.period = period self.start = start self.last_run = None def _next_run(self, utc): if utc: now = datetime.utcnow().replace(microsecond=0) else: now = datetime.now().replace(microsecond=0) if self.last_run is None: if self.start is not None: if isinstance(self.start, time): d1 = datetime.combine(datetime.min, self.start) d2 = datetime.combine(datetime.min, now.time()) self.start = timedelta(seconds=(d1 - d2).seconds) self.last_run = now + self.start else: self.last_run = now elif self.period is None: return else: while self.last_run <= now: self.last_run += self.period return self.last_run - now async def run(self, app, utc=True): while True: delta = self._next_run(utc) if delta is None: logger.info('STOP TASK "%s"' % self.func_name) break logger.debug('NEXT TASK "%s" %s' % (self.func_name, delta)) await asyncio.sleep(int(delta.total_seconds())) logger.info('RUN TASK "%s"' % self.func_name) try: ret = self.func(app) if inspect.isawaitable(ret): await ret logger.info('END TASK "%s"' % self.func_name) except Exception as e: logger.error(e) logger.error(traceback.format_exc())
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/scheduler/__sanic.py
__sanic.py
from datetime import datetime, timedelta from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR class Scheduler(object): """learning: https://blog.csdn.net/somezz/article/details/83104368""" def __init__(self): """ trigger='date': 一次性任务,即只执行一次任务。 next_run_time (datetime|str) – 下一次任务执行时间 timezone (datetime.tzinfo|str) – 时区 trigger='interval': 循环任务,即按照时间间隔执行任务。 seconds (int) – 秒 minutes (int) – 分钟 hours (int) – 小时 days (int) – 日 weeks (int) – 周 start_date (datetime|str) – 启动开始时间 end_date (datetime|str) – 最后结束时间 timezone (datetime.tzinfo|str) – 时区 trigger='cron': 定时任务,即在每个时间段执行任务。None为0 second (int|str) – 秒 (0-59) minute (int|str) – 分钟 (0-59) hour (int|str) – 小时 (0-23) day_of_week (int|str) – 一周中的第几天 (0-6 or mon,tue,wed,thu,fri,sat,sun) day (int|str) – 日 (1-31) week (int|str) – 一年中的第几周 (1-53) month (int|str) – 月 (1-12) year (int|str) – 年(四位数) start_date (datetime|str) – 最早开始时间 end_date (datetime|str) – 最晚结束时间 timezone (datetime.tzinfo|str) – 时区 """ self.scheduler = BackgroundScheduler() def add_job(self, func, trigger='interval', args=None, kwargs=None, max_instances=1, next_run_time=None, **trigger_args): """ The ``trigger`` argument can either be: #. the alias name of the trigger (e.g. ``date``, ``interval`` or ``cron``), in which case any extra keyword arguments to this method are passed on to the trigger's constructor #. an instance of a trigger class :param func: callable (or a textual reference to one) to run at the given time :param str|apscheduler.triggers.base.BaseTrigger trigger: trigger that determines when ``func`` is called :param list|tuple args: list of positional arguments to call func with :param dict kwargs: dict of keyword arguments to call func with next_run_time: 默认立即执行 可设置第一次的执行时间 None为暂停job """ assert callable(func), "TODO: callable function" self.scheduler.add_job(func, trigger, args, kwargs, max_instances=max_instances, next_run_time=next_run_time, **trigger_args) def add_listener(self, callback): assert callable(callback), "TODO: callable function" self.scheduler.add_listener(callback, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR) def start(self): self.scheduler.start() if __name__ == '__main__': # import logging # # logging.basicConfig(level=logging.INFO, # format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', # datefmt='%Y-%m-%d %H:%M:%S', # filename='log.txt', # filemode='a') # scheduler.scheduler._logger = logging def task1(x): print(x) import logging import time logging.warning(f'Task1: {time.ctime()}') def task2(): import logging import time logging.warning(f'Task2: {time.ctime()}') def task3(): import logging import time logging.warning(f'Task3: {time.ctime()}') def my_listener(event): if event.exception: # print(event.traceback) print('任务出错了!!!!!!') else: print('任务照常运行...') scheduler = Scheduler() scheduler.add_job(task1, 'interval', seconds=66666, args=('定时任务',)) scheduler.add_job(task2, 'interval', seconds=66666) scheduler.add_job(task3, 'cron', second=None, minute='*', hour='*') # scheduler.add_listener(my_listener) scheduler.start() while 1: pass
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/scheduler/Scheduler.py
Scheduler.py
from meutils.pipe import * from flask import abort, request from wechatpy.enterprise import create_reply, parse_message from wechatpy.enterprise.crypto import WeChatCrypto from flask import Blueprint, Flask import jieba # 应用ID # 回调模式里面随机生成的那个Token,EncodingAESKey sCorp_Id = 'ww3c6024bb94ecef59' sToken = 'Rt1GEhMOXt1Ea' sEncodingAESKey = 'so4rZ1IBA3cYXEvWZHciWd2oFs1qdZeN3UNExD5UmDK' crypto = WeChatCrypto(token=sToken, encoding_aes_key=sEncodingAESKey, corp_id=sCorp_Id) app = Flask(__name__) # 对应回调模式中的URL @app.route('/index', methods=['GET', 'POST']) def weixin(): msg_signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') if request.method == 'GET': echo_str = signature(request) logger.info(echo_str) return echo_str # 收到 raw_message = request.data decrypted_xml = crypto.decrypt_message( raw_message, msg_signature, timestamp, nonce ) msg = parse_message(decrypted_xml) logger.info(msg) """ TextMessage(OrderedDict([('ToUserName', 'ww3c6024bb94ecef59'), ('FromUserName', '7683'), ('CreateTime', '1648109637'), ('MsgType', 'text'), ('Content', '42156'), ('MsgId', '401559451'), ('AgentID', '1000041')])) """ _msg = msg.content.strip() flag = params = None if _msg: _ = msg.content.split(maxsplit=1) flag = _[0] params = _[1:] | xjoin() # 回复 if flag.__contains__('分词'): _msg = jieba.lcut(params.strip()) | xjoin() logger.info(_msg) xml = create_reply(str(_msg), msg).render() encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp) return encrypted_xml def signature(request): msg_signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echo_str = request.args.get('echostr', '') print(request.args) try: # 认证并对echo_str进行解密并返回明文 echo_str = crypto.check_signature(msg_signature, timestamp, nonce, echo_str) print(echo_str) except Exception as ex: print(ex) print(request) abort(403) return echo_str if __name__ == '__main__': app.run(host='0.0.0.0', port='5000', debug=True)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_fastapi/wecom_callback_.py
wecom_callback_.py
from meutils.pipe import * from wechatpy.replies import * from wechatpy.enterprise import create_reply, parse_message from wechatpy.enterprise.events import * from wechatpy.enterprise.crypto import WeChatCrypto import jieba # ME from appzoo import App from fastapi import FastAPI, Form, Depends, File, UploadFile, Body, Request, Response, Form, Cookie # 应用ID # 回调模式里面随机生成的那个Token,EncodingAESKey sCorp_Id = 'ww3c6024bb94ecef59' sToken = 'Rt1GEhMOXt1Ea' sEncodingAESKey = 'so4rZ1IBA3cYXEvWZHciWd2oFs1qdZeN3UNExD5UmDK' crypto = WeChatCrypto(token=sToken, encoding_aes_key=sEncodingAESKey, corp_id=sCorp_Id) app = App() app_ = app.app def ai_reply(reply, nonce, timestamp): xml = create_reply(reply, render=True) encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp) return encrypted_xml @app.api_route('/index', methods=['GET', 'POST']) async def weixin(request: Request): msg_signature = request.query_params.get('msg_signature', '') timestamp = request.query_params.get('timestamp', '') nonce = request.query_params.get('nonce', '') echo_str = request.query_params.get('echostr', '') if request.method == 'GET': # 认证并对echo_str进行解密并返回明文 echo_str = crypto.check_signature(msg_signature, timestamp, nonce, echo_str) logger.info(echo_str) return echo_str # 收到 raw_message = await request.body() decrypted_xml = crypto.decrypt_message( raw_message, msg_signature, timestamp, nonce ) msg = parse_message(decrypted_xml) logger.info(msg) logger.info(msg._data) """ TextMessage(OrderedDict([('ToUserName', 'ww3c6024bb94ecef59'), ('FromUserName', '7683'), ('CreateTime', '1648109637'), ('MsgType', 'text'), ('Content', '42156'), ('MsgId', '401559451'), ('AgentID', '1000041')])) """ if msg.type == 'event' and isinstance(msg, PicPhotoOrAlbumEvent): _msg = ImageReply(media_id=app.media_id) return ai_reply(_msg, nonce, timestamp) elif msg.type == 'image': app.media_id = msg.image.media_id elif msg.type == 'text': _msg = msg.content.strip() # todo return ai_reply(_msg, nonce, timestamp) # # # # 回复 # if flag.__contains__('分词'): # _msg = jieba.lcut(params.strip()) | xjoin() # logger.info(_msg) if __name__ == '__main__': app.run(app.app_from(__file__), port=5000, debug=True)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_fastapi/wecom_callback_fastapi.py
wecom_callback_fastapi.py
from meutils.pipe import * from meutils.zk_utils import * from meutils.datamodels.ArticleInfo import ArticleInfo from bertzoo.utils.bert4keras_utils import * # cfg @zk.DataWatch('/mipush/nh_model') def watcher(data, stat): # (data, stat, event) ZKConfig.info = yaml.safe_load(data) cfg = get_zk_config('/mipush/nh_model') vocab_url = cfg['vocab_url'] nh_bert_model_url_strict = cfg['nh_bert_model_url']['strict'] nh_bert_model_url_nostrict = cfg['nh_bert_model_url']['nostrict'] # loose nh_lgb_model_url_strict = cfg['nh_lgb_model_url']['strict'] nh_lgb_model_url_nostrict = cfg['nh_lgb_model_url']['nostrict'] # loose # download if not Path('vocab.txt').exists(): download(vocab_url, 'vocab.txt') tokenizer = Tokenizer('vocab.txt', do_lower_case=True) text2seq = functools.partial(text2seq, tokenizer=tokenizer) # hook: partial(DoubleBarrier, self) download(nh_bert_model_url_strict, 'nh_bert_strict') download(nh_bert_model_url_nostrict, 'nh_bert_nostrict') download(nh_lgb_model_url_strict, 'nh_lgb_strict') download(nh_lgb_model_url_nostrict, 'nh_lgb_nostrict') # load nh_bert_strict = keras.models.load_model('nh_bert_strict', compile=False) nh_bert_nostrict = keras.models.load_model('nh_bert_nostrict', compile=False) nh_lgb_strict = joblib.load('nh_lgb_strict') nh_lgb_nostrict = joblib.load('nh_lgb_nostrict') logger.info("初始化KerasModel") logger.info(nh_bert_strict.predict(text2seq("文本"))) logger.info(nh_bert_nostrict.predict(text2seq("文本"))) # 打分融合 @logger.catch() def merge_score(X, text="", mode_type='strict'): if mode_type == 'strict': weight = ZKConfig.info.get('lgb_weight_strict', 0.8) threshold = ZKConfig.info.get('threshold_strict', 0.9) pred1 = nh_lgb_strict.predict_proba(X)[:, 1].tolist()[0] pred2 = nh_bert_strict.predict(text2seq(text))[:, 1].tolist()[0] else: weight = ZKConfig.info.get('lgb_weight_nostrict', 0.8) threshold = ZKConfig.info.get('threshold_nostrict', 0.9) pred1 = nh_lgb_nostrict.predict_proba(X)[:, 1].tolist()[0] pred2 = nh_bert_nostrict.predict(text2seq(text))[:, 1].tolist()[0] pred = pred1 * weight + pred2 * (1 - weight) _ = { 'checkSuggestion': 'PASS' if pred > threshold else 'REVIEW', 'prob': [pred1, pred2], 'weight': weight, 'threshold': threshold } return _ def get_feats(ac): # logger.info(ac) # close logger _ = ac.pop('category') articleInfo = ArticleInfo(**ac) d = articleInfo.dict() del d['id'], d['title'], d['nCategory1'], d['nSubCategory1'] dt_feat = d.pop('createTime') + d.pop('publishTime') r = list(d.values()) + dt_feat return [r] # Api # @logger.catch def predict_strict(**ac): X = get_feats(ac) text = ac.get("title", "请输入一个文本") return merge_score(X, text, 'strict') def predict_nostrict(**ac): X = get_feats(ac) text = ac.get("title", "请输入一个文本") return merge_score(X, text, 'nostrict') if __name__ == '__main__': from appzoo import App app = App(verbose=os.environ.get('verbose')) app.add_route('/nh/strict', predict_strict, method="POST") app.add_route('/nh/nostrict', predict_nostrict, method="POST") app.run(port=8000, access_log=False)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_fastapi/nh_choice_model.py
nh_choice_model.py
from flask import Flask, request from wecom.tx import WXBizMsgCrypt import xml.etree.cElementTree as ET from meutils.pipe import * app = Flask(__name__) ############################################################################ sToken = 'Rt1GEhMOXt1Ea' sEncodingAESKey = 'so4rZ1IBA3cYXEvWZHciWd2oFs1qdZeN3UNExD5UmDK' sCorpID = 'ww3c6024bb94ecef59' wxcpt = WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID) ############################################################################ @app.route('/index', methods=['GET', 'POST']) def index(): # 获取url验证时微信发送的相关参数 sVerifyMsgSig = request.args.get('msg_signature') sVerifyTimeStamp = request.args.get('timestamp') sVerifyNonce = request.args.get('nonce') sVerifyEchoStr = request.args.get('echostr') logger.info(f"sVerifyEchoStr: {sVerifyEchoStr}") # sReqMsgSig = sVerifyMsgSig sReqTimeStamp = sVerifyTimeStamp sReqNonce = sVerifyNonce # 验证url if request.method == 'GET': ret, sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr) print(type(ret)) print(type(sEchoStr)) if (ret != 0): print(f"ERR: VerifyURL ret:{ret}") sys.exit(1) return sEchoStr # 接收客户端消息 if request.method == 'POST': # sReqMsgSig = request.form.get('msg_signature') # sReqTimeStamp = request.form.get('timestamp') # sReqNonce = request.form.get('nonce') # 赋值url验证请求相同的参数,使用上面注释掉的request.form.get方式获取时,测试有问题 sReqData = request.data print(sReqData) ret, sMsg = wxcpt.DecryptMsg(sReqData, sReqMsgSig, sReqTimeStamp, sReqNonce) if (ret != 0): print("ERR: VerifyURL ret:") sys.exit(1) # 解析发送的内容并打印 xml_tree = ET.fromstring(sMsg) content = xml_tree.find("Content").text ##############################图灵机器人 url = 'http://www.tuling123.com/openapi/api' a = requests.get(url, dict(key='3ac26126997942458c0d93de30d52212', info=content)).json() content = a.get('text', content) logger.info(a) ############################## # 被动响应消息,将微信端发送的消息返回给微信端 sRespData = f""" <xml> <ToUserName><![CDATA[mycreate]]></ToUserName> <FromUserName><![CDATA[wx177d1233ab4b730b]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[{content}]]></Content> <MsgId>1234567890123456</MsgId> <AgentID>1</AgentID> </xml>""" ret, sEncryptMsg = wxcpt.EncryptMsg(sRespData, sReqNonce, sReqTimeStamp) if (ret != 0): print("ERR: EncryptMsg ret: " + ret) sys.exit(1) return sEncryptMsg if __name__ == '__main__': app.run(host='0.0.0.0', port='5000', debug=True)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_fastapi/wecom_callback.py
wecom_callback.py
from meutils.common import * from meutils.np_utils import normalize from meutils.zk_utils import get_zk_config from appzoo import App import tensorflow as tf keras = tf.keras os.environ['TF_KERAS'] = '1' from bert4keras.models import build_transformer_model from bert4keras.tokenizers import Tokenizer from bert4keras.snippets import sequence_padding # BERT_DIR BERT_DIR = './chinese_simbert_L-12_H-768_A-12' fds_url = get_zk_config("/mipush/cfg")['fds_url'] if not os.path.exists(BERT_DIR): url = f"{fds_url}/data/bert/chinese_simbert_L-12_H-768_A-12.zip" os.system(f"wget {url} && unzip chinese_simbert_L-12_H-768_A-12.zip") config_path = f'{BERT_DIR}/bert_config.json' checkpoint_path = f'{BERT_DIR}/bert_model.ckpt' dict_path = f'{BERT_DIR}/vocab.txt' # 建立分词器 tokenizer = Tokenizer(dict_path, do_lower_case=True) # 建立加载模型 bert = build_transformer_model( config_path, checkpoint_path, with_pool='linear', application='unilm', return_keras_model=False # True: bert.predict([np.array([token_ids]), np.array([segment_ids])]) ) encoder = keras.models.Model(bert.model.inputs, bert.model.outputs[0]) # seq2seq = keras.models.Model(bert.model.inputs, bert.model.outputs[1]) maxlen = 64 @lru_cache(100000) def text2vec(text): token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen) data = [sequence_padding([token_ids], length=maxlen), sequence_padding([segment_ids], length=maxlen)] vecs = encoder.predict(data) return vecs def texts2vec(texts): X = [] S = [] for text in texts: token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen) X.append(token_ids) S.append(segment_ids) data = [sequence_padding(X, length=maxlen), sequence_padding(S, length=maxlen)] vecs = encoder.predict(data) return vecs # # collection # from mi.db import Mongo # m = Mongo() # cache_bert = m.db['cache_bert'] # def get_one_vec(**kwargs): # text = kwargs.get('text', '默认') # is_lite = kwargs.get('is_lite', '0') # # doc = cache_bert.find_one({'text': text}) # # if doc: # logger.info(f'dup key: {text}') # vecs = doc['vector'] # else: # vecs = text2vec(text) # vecs = normalize(vecs).tolist() # # cache_bert.insert_one({'text': text, 'vector': vecs}) # # if is_lite == '0': # return vecs # else: # vecs = np.array(vecs)[:, range(0, 768, 4)] # return normalize(vecs).tolist() # 64*3 = 192维度 def get_one_vec(**kwargs): text = kwargs.get('text', '默认') is_lite = kwargs.get('is_lite', '0') vecs = text2vec(text) if is_lite == '1': vecs = vecs[:, range(0, 768, 4)] # 64*3 = 192维度 return normalize(vecs).tolist() def get_batch_vec(**kwargs): texts = kwargs.get('texts', ['默认']) is_lite = kwargs.get('is_lite', '0') vecs = texts2vec(texts) if is_lite == '1': vecs = vecs[:, range(0, 768, 4)] # 64*3 = 192维度 return normalize(vecs).tolist() if __name__ == '__main__': logger.info(f"初始化初始化模型: {text2vec('语言模型')}") # 不初始化会报线程错误 app = App(verbose=os.environ.get('verbose')) app.add_route('/simbert', get_one_vec, result_key='vectors') app.add_route('/simbert', get_batch_vec, 'POST', result_key='vectors') app.run(access_log=False)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_fastapi/simbert_app.py
simbert_app.py
from meutils.common import * from meutils.zk_utils import get_zk_config from appzoo import App from paddleocr import PaddleOCR from PIL import Image ac_url = get_zk_config('/mipush/cfg')['ac_url'] ocr = PaddleOCR(use_angle_cls=True, lang="ch") def request(url, json=None, method='get'): r = requests.request(method, url, json=json) r.encoding = r.apparent_encoding return r.json() def get_ocr_result(**kwargs): image_urls = kwargs.get('image_urls', []) results = [] for image_url in image_urls: os.system(f"wget -q {image_url} -O image") result = ocr.ocr('image', cls=True) # todo results.append(result) os.system(f"rm image") return eval(str(results)) def text_match_flag(image_result, w, h): cp2flags = get_zk_config('/mipush/ocr') for text_loc, (text, _) in image_result: text = text.strip().lower() for cp, flags in cp2flags.items(): for flag in flags: if text.__contains__(flag): text_loc = np.array(text_loc).mean(0) text_loc_ = text_loc - (w / 2, h / 2) return cp, text, text_loc_.tolist() def get_water_mark(**kwargs): """ # 负负左上角 # 正正右下角 # 正负右上角 # 负正左下角 """ image_urls = kwargs.get('image_urls', []) results = [] for image_url in image_urls: os.system(f"wget -q {image_url} -O water_mark_image") w, h = Image.open('image').size image_result = ocr.ocr('image', cls=True) # todo results.append(text_match_flag(image_result, w, h)) os.system(f"rm water_mark_image") return results def get_water_mark_from_docid(**kwargs): docid = kwargs.get('docid', '0003899b202871b7fd3dab15f2f9549a') url = f'{ac_url}/{docid}' ac = request(url)['item'] return get_water_mark(image_urls=list(ac['imageFeatures'])) app_ = App() app_.add_route('/ocr', get_ocr_result, method="POST") app_.add_route('/ocr/water_mark', get_water_mark, method="POST") app_.add_route('/ocr/water_mark', get_water_mark_from_docid, method="GET") app = app_.app if __name__ == '__main__': # app.run(port=9955, debug=False, reload=False) app_.run(f"{app_.app_file_name(__file__)}", port=9955, access_log=False, debug=False, reload=False)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_fastapi/ocr_app.py
ocr_app.py
from fastapi import FastAPI from starlette.requests import Request import pandas as pd from miwork.feishu import Feishu from meutils.http_utils import request from meutils.str_utils import unquote from meutils.log_utils import logger4feishu app = FastAPI() fs = Feishu() @app.post("/hive/{chat}/{title}") async def hive_http_callback(request: Request, chat, title, isimage: int = 1, image_desc='我是个数据框'): """ chat: 多个群逗号分割不要带空格 数据工厂http回调 """ chats = unquote(chat).strip().split(',') # 解码比较靠谱 data_str = dict(await request.form()).get('data', '') if data_str: data = eval(data_str) df = pd.DataFrame(data[1:], columns=data[0]) else: df = pd.DataFrame() if isimage: for chat in chats: fs.send_by_df_card( chat=chat, title=title, subtitle='', df=df, image_desc=image_desc ) else: for chat in chats: fs.send_by_card( chat=chat, # 'PUSH算法组', title=title, text=df.to_string(index=False), md_text="", ) @app.get("/common/{chat}/{title}") def send_by_card_get(request: Request, chat, title): """ /common/PUSH算法组/我是个标题?text=我是条内容 """ input = dict(request.query_params) text = input.get('text', '') fs.send_by_card(chat=chat, title=title, text="", md_text=text) @app.post("/common/{chat}/{title}") def send_by_card_post(chat, title, kwargs: dict): text = kwargs.get('text', '') fs.send_by_card(chat=chat, title=title, text="", md_text=text) # wehooks @app.post("/wehook") def wehook(kwargs: dict): """wehooks 内网穿透 解决网络不通的问题 body = { 'url': 'wehook_url', 'post': {'title': '我是个标题', 'text': '我是条内容'} } """ url = kwargs.get('url') post = kwargs.get('post') return request(url, json=post) # card @app.post("/image") def send_df(kwargs: dict): """目前支持dataframe发送 body = { "chat": "PUSH算法组", "title": "我是个标题", "subtitle": "我是个副标题", "image_desc": "我是个数据框", "df_json": [{"a": 1, "b": 2}] } """ df = pd.DataFrame(kwargs.get('df_json')) fs.send_by_df_card(chat=kwargs.get('chat', 'PUSH算法组'), title=kwargs.get('title', '我是一个标题'), subtitle=kwargs.get('subtitle', ''), df=df, image_desc=kwargs.get('image_desc', '我是个数据框')) @app.get("/logger/{title}") def logger_get(request: Request, title): kwargs = dict(request.query_params) logger4feishu(title, kwargs.get('text', '我是个log')) @app.post("/logger") def logger_post(kwargs: dict): """ { "title": "我是个标题", "text": "我是个log", } """ logger4feishu(title=kwargs.get('title', '我是个标题'), text=kwargs.get('text', '我是个log')) if __name__ == '__main__': import uvicorn uvicorn.run(app, host='0.0.0.0')
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_fastapi/feishu_bot_app.py
feishu_bot_app.py
from meutils.common import * from meutils.zk_utils import get_zk_config from appzoo import App from paddleocr import PaddleOCR from PIL import Image ocr = PaddleOCR(use_angle_cls=True, lang="ch") def request(url, json=None, method='get'): r = requests.request(method, url, json=json) r.encoding = r.apparent_encoding return r.json() def get_ocr_result(**kwargs): image_urls = kwargs.get('image_urls', []) results = [] for image_url in image_urls: os.system(f"wget -q {image_url} -O image") result = ocr.ocr('image', cls=True) # todo results.append(result) os.system(f"rm image") return eval(str(results)) def text_match_flag(image_result, w, h): cp2flags = get_zk_config('/mipush/ocr') for text_loc, (text, _) in image_result: text = text.strip().lower() for cp, flags in cp2flags.items(): for flag in flags: if text.__contains__(flag): text_loc = np.array(text_loc).mean(0) text_loc_ = text_loc - (w / 2, h / 2) return cp, text, text_loc_.tolist() def get_water_mark(**kwargs): """ # 负负左上角 # 正正右下角 # 正负右上角 # 负正左下角 """ image_urls = kwargs.get('image_urls', []) results = [] for image_url in image_urls: os.system(f"wget -q {image_url} -O water_mark_image") w, h = Image.open('image').size image_result = ocr.ocr('image', cls=True) # todo results.append(text_match_flag(image_result, w, h)) os.system(f"rm water_mark_image") return results def get_water_mark_from_docid(**kwargs): docid = kwargs.get('docid', '0003899b202871b7fd3dab15f2f9549a') url = f'{ac_url}/{docid}' ac = request(url)['item'] return get_water_mark(image_urls=list(ac['imageFeatures'])) app_ = App() app_.add_route('/ocr', get_ocr_result, method="POST") app_.add_route('/ocr/water_mark', get_water_mark, method="POST") app_.add_route('/ocr/water_mark', get_water_mark_from_docid, method="GET") app = app_.app if __name__ == '__main__': # app.run(port=9955, debug=False, reload=False) app_.run(f"{app_.app_file_name(__file__)}", port=9955, access_log=False, debug=False, reload=False)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_fastapi/ocr_app_.py
ocr_app_.py
import grpc from appzoo.grpc_app.utils import _options from appzoo.grpc_app.protos.base_pb2 import Request, Response from appzoo.grpc_app.protos.base_pb2_grpc import GrpcServiceServicer, GrpcServiceStub, add_GrpcServiceServicer_to_server from meutils.pipe import * from pickle import dumps, loads class Service(GrpcServiceServicer): def __init__(self, debug=False, options=None): self.debug = debug self.options = options if options else _options def main(self, *args, **kwargs): """主逻辑""" raise NotImplementedError('Method not implemented!') @logger.catch() def _request(self, request, context): input = loads(request.data) # 反序列化 if self.debug: logger.debug(input) try: output = self.main(input) except Exception as e: output = {'error': e} return Response(data=dumps(output)) # 序列化 def run(self, port=8000, max_workers=None, is_async=False): if is_async: loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait([self.async_server()])) loop.close() server = grpc.server(ThreadPoolExecutor(max_workers), options=self.options) # compression = None add_GrpcServiceServicer_to_server(self, server) server.add_insecure_port(f'[::]:{port}') logger.info("GrpcService Running ...") logger.info(f"{LOCAL_HOST}:{port}") server.start() server.wait_for_termination() async def async_server(self, port=8000, max_workers=None): server = grpc.aio.server(ThreadPoolExecutor(max_workers), options=self.options) add_GrpcServiceServicer_to_server(self, server) server.add_insecure_port(f'[::]:{port}') logger.info("Async GrpcService Running ...") logger.info(f"{LOCAL_HOST}:{port}") await server.start() await server.wait_for_termination() if __name__ == '__main__': class MyService(Service): def main(self, data): 1 / 0 # from meutils.path_utils import import_mains # # mains = import_mains('multi_apps') # # class MyService(Service): # # def main(self, data): # method, data = data # if method in mains: # return mains[method](data) MyService(debug=True).run(max_workers=2)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/grpc_app/service.py
service.py
"""Client and server classes corresponding to protobuf-defined services.""" import grpc from appzoo.grpc_app.protos import base_pb2 as base__pb2 class GrpcServiceStub(object): """定义服务接口 """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self._request = channel.unary_unary( '/GrpcService/_request', request_serializer=base__pb2.Request.SerializeToString, response_deserializer=base__pb2.Response.FromString, ) class GrpcServiceServicer(object): """定义服务接口 """ def _request(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GrpcServiceServicer_to_server(servicer, server): rpc_method_handlers = { '_request': grpc.unary_unary_rpc_method_handler( servicer._request, request_deserializer=base__pb2.Request.FromString, response_serializer=base__pb2.Response.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'GrpcService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class GrpcService(object): """定义服务接口 """ @staticmethod def _request(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/GrpcService/_request', base__pb2.Request.SerializeToString, base__pb2.Response.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/grpc_app/protos_/base_pb2_grpc.py
base_pb2_grpc.py
"""Client and server classes corresponding to protobuf-defined services.""" import grpc from appzoo.grpc_app.protos import base_pb2 as base__pb2 class GrpcServiceStub(object): """定义服务接口 """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self._request = channel.unary_unary( '/GrpcService/_request', request_serializer=base__pb2.Request.SerializeToString, response_deserializer=base__pb2.Response.FromString, ) class GrpcServiceServicer(object): """定义服务接口 """ def _request(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GrpcServiceServicer_to_server(servicer, server): rpc_method_handlers = { '_request': grpc.unary_unary_rpc_method_handler( servicer._request, request_deserializer=base__pb2.Request.FromString, response_serializer=base__pb2.Response.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'GrpcService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class GrpcService(object): """定义服务接口 """ @staticmethod def _request(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/GrpcService/_request', base__pb2.Request.SerializeToString, base__pb2.Response.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/grpc_app/protos/base_pb2_grpc.py
base_pb2_grpc.py
import functools from zipfile import ZipFile from meutils.pipe import * import textwrap import streamlit as st from streamlit.components.v1 import html from streamlit.elements.image import image_to_url def hide_st_style(footer_content='🔥'): _ = """ <style> #MainMenu {visibility: hidden;} footer {visibility: hidden;} header {visibility: hidden;} </style> """ _ = f""" <style>.css-18e3th9 {{padding-top: 2rem;}} #MainMenu {{visibility: hidden;}} header {{visibility: hidden;}} footer {{visibility: hidden;}} footer:after {{content:"{footer_content}";visibility: visible;display: block;position: 'fixed';}} </style> """ st.markdown(_, unsafe_allow_html=True) def set_footer(prefix="Made with 🔥 by ", author='Betterme', url=None): # 链接门户、微信 _ = f""" <style> .footer {{ position: fixed; left: 0; bottom: 0; width: 100%; background-color: #F5F5F5; color: #000000; text-align: center; border-style: solid; border-width: 1px; border-color: #DDDDDD; padding: 8px; }} </style> <div class="footer"> <p>{prefix}<a href="{url}" target="_blank">{author}</a></p> </div> """ st.markdown(_, unsafe_allow_html=True) # 设置文本字体 def set_font(): _ = f""" <style> h1,h2,h3,h4,h5,h6 {{ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 400; }} </style> """ st.markdown(_, unsafe_allow_html=True) # 设置页面背景色 def set_background_color(color='#f1f1f1'): _ = f""" <style> body {{ background-color: {color}; }} </style> """ st.markdown(_, unsafe_allow_html=True) def set_background_image(image=get_module_path('./pics/夕阳.png', __file__)): image_url = image_to_url(image, width=-1, clamp=False, channels="RGB", output_format="auto", image_id="") _ = f''' <style> .css-fg4pbf {{ background-image:url({image_url}); background-repeat: no-repeat; background-size: cover; background-position: center center; height: 100vh; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; }} </style> ''' st.markdown(_, unsafe_allow_html=True) def set_space(num_lines=1): """Adds empty lines to the Streamlit app.""" for _ in range(num_lines): st.write("") def set_columns_placed(bins=2, default_position=0, gap='small'): # ("small", "medium", or "large") _ = st.columns(spec=bins, gap=gap) if len(_) < default_position: default_position = -1 return _[default_position] def show_code(func): """Showing the code of the demo.""" _ = st.sidebar.checkbox("Show code", False) if _: # Showing the code of the demo. st.markdown("---") st.markdown("## Main Code") sourcelines, _ = inspect.getsourcelines(func) st.code(textwrap.dedent("".join(sourcelines[1:]))) st.markdown("---") def display_pdf(base64_pdf, width='100%', height=1000): _ = f"""<embed src="data:application/pdf;base64,{base64_pdf}" width="{width}" height="{height}" type="application/pdf">""" st.markdown(_, unsafe_allow_html=True) def display_pdf4file(file, width='100%', height=500): # 上传PDF文件 base64_pdf = base64.b64encode(file.read()).decode('utf-8') display_pdf(base64_pdf, width, height) def display_html(text='会飞的文字'): # html("""<marquee bgcolor="#00ccff" behavior="alternate">这是一个滚动条</marquee>""") _ = f""" <marquee direction="down" width="100%" height="100%" behavior="alternate" style="border:solid" bgcolor="#00FF00"> <marquee behavior="alternate"> {text} </marquee> </marquee> """ st.markdown(_, unsafe_allow_html=True) def reply4input( input, history=None, reply_func=lambda input: f'{input}的答案', max_turns=3, container=None, previous_messages=None, user_avatar_style="adventurer", bot_avatar_style="Big Smile", seed=42, ): """https://www.dicebear.com/styles/big-smile container = st.container() # 占位符 text = st.text_area(label="用户输入", height=100, placeholder="请在这儿输入您的问题") if st.button("发送", key="predict"): with st.spinner("AI正在思考,请稍等........"): history = st.session_state.get('state') st.session_state["state"] = reply4input(text, history, container=container) print(st.session_state['state']) """ from streamlit_chat import message user_message = partial(message, avatar_style=user_avatar_style.strip().replace(' ', '-').lower(), is_user=True, seed=seed) bot_message = partial(message, avatar_style=bot_avatar_style.strip().replace(' ', '-').lower(), is_user=False, seed=seed) if history is None: history = [] # [(input/query, response)] if container is None: container = st.container() with container: if previous_messages: for msg in previous_messages: bot_message(msg) # display all the previous message if max_turns > 1 and len(history) > 0: # 展示历史 for i, (query, response) in enumerate(history[-max_turns + 1:]): user_message(query, key=str(i) + "_user") bot_message(response, key=str(i)) user_message(input, key=str(len(history)) + "_user") # st.write("AI正在回复:") with st.empty(): response = reply_func(input) if isinstance(response, types.GeneratorType): for i, _response in enumerate(response): bot_message(_response, key=f"stream{i}") response = _response else: bot_message(response) history.append((input, response)) return history def set_popupwindow(title='这是一个弹窗', text='### 这是一个弹窗内容', padding=20, max_width=None): # todo: 模仿写插件 from streamlit_modal import Modal modal = Modal(title, title, padding, max_width) if st.button("一键预测"): modal.open() if modal.is_open(): with modal.container(): pass def set_button(): css = """<style> .stDownloadButton>button { background-color: #0099ff; color:#ffffff; } .stDownloadButton>button:hover { background-color: #00ff00; color:#ff0000; } </style> """ html(css) # st.markdown
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/streamlit_app/utils.py
utils.py
import os import streamlit.components.v1 as components # Create a _RELEASE constant. We'll set this to False while we're developing # the component, and True when we're ready to package and distribute it. # (This is, of course, optional - there are innumerable ways to manage your # release process.) _RELEASE = True # Declare a Streamlit component. `declare_component` returns a function # that is used to create instances of the component. We're naming this # function "_component_func", with an underscore prefix, because we don't want # to expose it directly to users. Instead, we will create a custom wrapper # function, below, that will serve as our component's public API. # It's worth noting that this call to `declare_component` is the # *only thing* you need to do to create the binding between Streamlit and # your component frontend. Everything else we do in this file is simply a # best practice. if not _RELEASE: _component_func = components.declare_component( # We give the component a simple, descriptive name ("my_component" # does not fit this bill, so please choose something better for your # own component :) "st_autorefresh", # Pass `url` here to tell Streamlit that the component will be served # by the local dev server that you run via `npm run start`. # (This is useful while your component is in development.) url="http://localhost:3001", ) else: # When we're distributing a production version of the component, we'll # replace the `url` param with `path`, and point it to to the component's # build directory: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _component_func = components.declare_component("st_autorefresh", path=build_dir) # Create a wrapper function for the component. This is an optional # best practice - we could simply expose the component function returned by # `declare_component` and call it done. The wrapper allows us to customize # our component's API: we can pre-process its input args, post-process its # output value, and add a docstring for users. def st_autorefresh(interval=1000, limit=None, key=None): """Create an autorefresh instance to trigger a refresh of the application Parameters ---------- interval: int Amount of time in milliseconds to limit: int or None Amount of refreshes to allow. If none, it will refresh infinitely. While infinite refreshes sounds nice, it will continue to utilize computing resources. key: str or None An optional key that uniquely identifies this component. If this is None, and the component's arguments are changed, the component will be re-mounted in the Streamlit frontend and lose its current state. Returns ------- int Number of times the refresh has been triggered or max value of int """ count = _component_func(interval=interval, limit=limit, key=key) if count is None: return 0 return int(count) # Add some test code to play with the component while it's in development. # During development, we can run this just as we would any other Streamlit # app: `$ streamlit run my_component/__init__.py` if not _RELEASE: import streamlit as st # We use the special "key" argument to assign a fixed identity to this # component instance. By default, when a component's arguments change, # it is considered a new instance and will be re-mounted on the frontend # and lose its current state. In this case, we want to vary the component's # "name" argument without having it get recreated. # Run the autorefresh about every 2000 milliseconds (2 seconds) and stop # after it's been refreshed 100 times. count = st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") # The function returns a counter for number of refreshes. This allows the # ability to make special requests at different intervals based on the count if count == 0: st.write("Count is zero") elif count % 3 == 0 and count % 5 == 0: st.write("FizzBuzz") elif count % 3 == 0: st.write("Fizz") elif count % 5 == 0: st.write("Buzz") else: st.write(f"Count: {count}")
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/streamlit_app/components_/streamlit_autorefresh/__init__.py
__init__.py
from meutils.common import * import streamlit as st from paddleocr import PaddleOCR from PIL import Image from appzoo.utils.image_utils import ocr_result_image from appzoo.utils.streamlit_utils import * ocr = PaddleOCR(use_angle_cls=True, lang="ch") ################################################################################################ def text_match_flag(image_result, w, h): cp2flags = get_zk_config('/mipush/ocr') for text_loc, (text, _) in image_result: text = text.strip().lower() for cp, flags in cp2flags.items(): for flag in flags: if text.__contains__(flag): text_loc = np.array(text_loc).mean(0) text_loc_ = text_loc - (w / 2, h / 2) return cp, text, text_loc_.tolist() ################################################################################################ # side st.sidebar.markdown('**OCR SideBar**') biz = st.sidebar.selectbox('输入方式', ('ImageUrl', 'ImageFile'), index=0) if biz == 'ImageUrl': ImageUrl = st.text_input( "ImageUrl", "https://i1.mifile.cn/f/i/mioffice/img/slogan_5.png?1604383825042" ) input_image = 'image.png' os.system(f"wget -q {ImageUrl} -O {input_image}") st.markdown("## 文字识别") image_result = ocr.ocr(input_image, cls=True) output_image = ocr_result_image(image_result, input_image) st.image(output_image) # st.json(image_result) st.markdown("## 水印识别") w, h = Image.open(input_image).size st.json({"水印识别": text_match_flag(image_result, w, h)}) # # st.markdown("## 水印召回词") # st.json({"zk已配置水印召回词": get_zk_config('/mipush/ocr')}) os.system(f"rm {input_image}") elif biz == 'ImageFile': input_image = file_uploader(st) if input_image: result = ocr.ocr(input_image, cls=True) output_image = ocr_result_image(result, input_image) st.image(output_image) st.json(result) os.system(f"rm {input_image}")
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_streamlit/ocr_app.py
ocr_app.py
from meutils.common import * from meutils.zk_utils import get_zk_config import streamlit as st from paddleocr import PaddleOCR from PIL import Image from appzoo.utils.image_utils import ocr_result_image from appzoo.utils.streamlit_utils import * ocr = PaddleOCR(use_angle_cls=True, lang="ch") ################################################################################################ def text_match_flag(image_result, w, h): cp2flags = get_zk_config('/mipush/ocr') for text_loc, (text, _) in image_result: text = text.strip().lower() for cp, flags in cp2flags.items(): for flag in flags: if text.__contains__(flag): text_loc = np.array(text_loc).mean(0) text_loc_ = text_loc - (w / 2, h / 2) return cp, text, text_loc_.tolist() ################################################################################################ # side st.sidebar.markdown('**OCR SideBar**') biz = st.sidebar.selectbox('输入方式', ('ImageUrl', 'ImageFile'), index=0) if biz == 'ImageUrl': ImageUrl = st.text_input( "ImageUrl", "https://i1.mifile.cn/f/i/mioffice/img/slogan_5.png?1604383825042" ) input_image = 'image.png' os.system(f"wget -q {ImageUrl} -O {input_image}") st.markdown("## 文字识别") image_result = ocr.ocr(input_image, cls=True) output_image = ocr_result_image(image_result, input_image) st.image(output_image) # st.json(image_result) st.markdown("## 水印识别") w, h = Image.open(input_image).size st.json({"水印识别": text_match_flag(image_result, w, h)}) st.markdown("## 水印召回词") st.json({"zk已配置水印召回词": get_zk_config('/mipush/ocr')}) os.system(f"rm {input_image}") elif biz == 'ImageFile': input_image = file_uploader(st) if input_image: result = ocr.ocr(input_image, cls=True) output_image = ocr_result_image(result, input_image) st.image(output_image) st.json(result) os.system(f"rm {input_image}")
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_streamlit/ocr_app_.py
ocr_app_.py
import streamlit as st import inspect import textwrap import pandas as pd import pydeck as pdk from streamlit.hello.utils import show_code from urllib.error import URLError def mapping_demo(): @st.cache def from_data_file(filename): url = ( "http://raw.githubusercontent.com/streamlit/" "example-data/master/hello/v1/%s" % filename ) return pd.read_json(url) try: ALL_LAYERS = { "Bike Rentals": pdk.Layer( "HexagonLayer", data=from_data_file("bike_rental_stats.json"), get_position=["lon", "lat"], radius=200, elevation_scale=4, elevation_range=[0, 1000], extruded=True, ), "Bart Stop Exits": pdk.Layer( "ScatterplotLayer", data=from_data_file("bart_stop_stats.json"), get_position=["lon", "lat"], get_color=[200, 30, 0, 160], get_radius="[exits]", radius_scale=0.05, ), "Bart Stop Names": pdk.Layer( "TextLayer", data=from_data_file("bart_stop_stats.json"), get_position=["lon", "lat"], get_text="name", get_color=[0, 0, 0, 200], get_size=15, get_alignment_baseline="'bottom'", ), "Outbound Flow": pdk.Layer( "ArcLayer", data=from_data_file("bart_path_stats.json"), get_source_position=["lon", "lat"], get_target_position=["lon2", "lat2"], get_source_color=[200, 30, 0, 160], get_target_color=[200, 30, 0, 160], auto_highlight=True, width_scale=0.0001, get_width="outbound", width_min_pixels=3, width_max_pixels=30, ), } st.sidebar.markdown("### Map Layers") selected_layers = [ layer for layer_name, layer in ALL_LAYERS.items() if st.sidebar.checkbox(layer_name, True) ] if selected_layers: st.pydeck_chart( pdk.Deck( map_style="mapbox://styles/mapbox/light-v9", initial_view_state={ "latitude": 37.76, "longitude": -122.4, "zoom": 11, "pitch": 50, }, layers=selected_layers, ) ) else: st.error("Please choose at least one layer above.") except URLError as e: st.error( """ **This demo requires internet access.** Connection error: %s """ % e.reason ) st.set_page_config(page_title="Mapping Demo", page_icon="🌍") st.markdown("# Mapping Demo") st.sidebar.header("Mapping Demo") st.write( """This demo shows how to use [`st.pydeck_chart`](https://docs.streamlit.io/library/api-reference/charts/st.pydeck_chart) to display geospatial data.""" ) mapping_demo() show_code(mapping_demo)
AppZoo
/AppZoo-2023.4.25.19.12.44.tar.gz/AppZoo-2023.4.25.19.12.44/appzoo/apps_streamlit/home/pages/2_🌍_Mapping_Demo.py
2_🌍_Mapping_Demo.py
.. :changelog: History ------- 0.1.0 (2014-10-13) ------------------ * First release on GitHub. 0.1.1 (2014-12-4) ----------------- * Add support for multi-kind JSON files 0.1.2 (2014-12-4) ----------------- * Minor fixes 0.1.3 (2014-12-5) ----------------- * Added support for PropertyKey-based child entities 0.1.4 (2015-2-4) ----------------- * Fixed bug in which post-processor was called on every property change * Added section on development to README.rst 0.1.5 (2015-2-11) ----------------- * Added `__children__` support * Added manual key definition through the `__id__` attribute 0.1.6 (2015-8-30) ----------------- * Builds if you don't have `curl` installed * Minor documentation improvements 0.1.7 (2015-11-3) ----------------- * Syntax highlighting on the documentation * Coverage analysis using Coveralls 0.1.8 (2016-02-05) ------------------ * New resources/Makefile 0.1.9 (2016-12-19) ------------------ * Replace pep8 with pycodestyle * Update current SDK version detection to latest version
Appengine-Fixture-Loader
/Appengine-Fixture-Loader-0.1.9.tar.gz/Appengine-Fixture-Loader-0.1.9/HISTORY.rst
HISTORY.rst
appengine-fixture-loader ======================== A simple way to load Django-like fixtures into the local development datastore, originally intended to be used by `testable_appengine <https://github.com/rbanffy/testable_appengine>`_. .. image:: https://img.shields.io/pypi/l/appengine-fixture-loader.svg :target: ./LICENSE .. image:: https://badge.fury.io/py/appengine-fixture-loader.svg :target: https://badge.fury.io/py/appengine-fixture-loader .. image:: https://api.travis-ci.org/rbanffy/appengine-fixture-loader.svg :target: https://travis-ci.org/rbanffy/appengine-fixture-loader .. image:: https://img.shields.io/pypi/pyversions/appengine-fixture-loader.svg :target: https://pypi.python.org/pypi/appengine-fixture-loader/ .. image:: https://img.shields.io/pypi/dm/appengine-fixture-loader.svg :target: https://pypi.python.org/pypi/appengine-fixture-loader/ .. image:: https://coveralls.io/repos/rbanffy/appengine-fixture-loader/badge.svg?branch=master&service=github :target: https://coveralls.io/github/rbanffy/appengine-fixture-loader?branch=master Installing ---------- For the less adventurous, Appengine-Fixture-Loader is available on PyPI at https://pypi.python.org/pypi/Appengine-Fixture-Loader. Single-kind loads ------------------ Let's say you have a model like this: .. code-block:: python class Person(ndb.Model): """Our sample class""" first_name = ndb.StringProperty() last_name = ndb.StringProperty() born = ndb.DateTimeProperty() userid = ndb.IntegerProperty() thermostat_set_to = ndb.FloatProperty() snores = ndb.BooleanProperty() started_school = ndb.DateProperty() sleeptime = ndb.TimeProperty() favorite_movies = ndb.JsonProperty() processed = ndb.BooleanProperty(default=False) If you want to load a data file like this: .. code-block:: javascript [ { "__id__": "jdoe", "born": "1968-03-03T00:00:00", "first_name": "John", "last_name": "Doe", "favorite_movies": [ "2001", "The Day The Earth Stood Still (1951)" ], "snores": false, "sleeptime": "23:00", "started_school": "1974-02-15", "thermostat_set_to": 18.34, "userid": 1 }, ... { "born": "1980-05-25T00:00:00", "first_name": "Bob", "last_name": "Schneier", "favorite_movies": [ "2001", "Superman" ], "snores": true, "sleeptime": "22:00", "started_school": "1985-08-01", "thermostat_set_to": 18.34, "userid": -5 } ] All you need to do is to: .. code-block:: python from appengine_fixture_loader.loader import load_fixture and then: .. code-block:: python loaded_data = load_fixture('tests/persons.json', kind=Person) In our example, `loaded_data` will contain a list of already persisted Person models you can then manipulate and persist again. The `__id__` attribute, when defined, will save the object with that given id. In our case, the key to the first object defined will be a `ndb.Key('Person', 'jdoe')`. The key may be defined on an object by object base - where the `__id__` parameter is omitted, an automatic id will be generated - the key to the second one will be something like `ndb.Key('Person', 1)`. Multi-kind loads ---------------- It's convenient to be able to load multiple kinds of objects from a single file. For those cases, we provide a simple way to identify the kind of object being loaded and to provide a set of models to use when loading the objects. Consider our original example model: .. code-block:: python class Person(ndb.Model): """Our sample class""" first_name = ndb.StringProperty() last_name = ndb.StringProperty() born = ndb.DateTimeProperty() userid = ndb.IntegerProperty() thermostat_set_to = ndb.FloatProperty() snores = ndb.BooleanProperty() started_school = ndb.DateProperty() sleeptime = ndb.TimeProperty() favorite_movies = ndb.JsonProperty() processed = ndb.BooleanProperty(default=False) and let's add a second one: .. code-block:: python class Dog(ndb.Model): """Another sample class""" name = ndb.StringProperty() Now, if we wanted to make a single file load objects of the two kinds, we'd need to use the `__kind__` attribute in the JSON: .. code-block:: javascript [ { "__kind__": "Person", "born": "1968-03-03T00:00:00", "first_name": "John", "last_name": "Doe", "favorite_movies": [ "2001", "The Day The Earth Stood Still (1951)" ], "snores": false, "sleeptime": "23:00", "started_school": "1974-02-15", "thermostat_set_to": 18.34, "userid": 1 }, { "__kind__": "Dog", "name": "Fido" } ] And, to load the file, we'd have to: .. code-block:: python from appengine_fixture_loader.loader import load_fixture and: .. code-block:: python loaded_data = load_fixture('tests/persons_and_dogs.json', kind={'Person': Person, 'Dog': Dog}) will result in a list of Persons and Dogs (in this case, one person and one dog). Multi-kind, multi-level loads ----------------------------- Anther common case is having hierarchies of entities that you want to reconstruct for your tests. Using slightly modified versions of our example classes: .. code-block:: python class Person(ndb.Model): """Our sample class""" first_name = ndb.StringProperty() last_name = ndb.StringProperty() born = ndb.DateTimeProperty() userid = ndb.IntegerProperty() thermostat_set_to = ndb.FloatProperty() snores = ndb.BooleanProperty() started_school = ndb.DateProperty() sleeptime = ndb.TimeProperty() favorite_movies = ndb.JsonProperty() processed = ndb.BooleanProperty(default=False) appropriate_adult = ndb.KeyProperty() and: .. code-block:: python class Dog(ndb.Model): """Another sample class""" name = ndb.StringProperty() processed = ndb.BooleanProperty(default=False) owner = ndb.KeyProperty() And using `__children__[attribute_name]__` like meta-attributes, as in: .. code-block:: javascript [ { "__kind__": "Person", "born": "1968-03-03T00:00:00", "first_name": "John", "last_name": "Doe", ... "__children__appropriate_adult__": [ { "__kind__": "Person", "born": "1970-04-27T00:00:00", ... "__children__appropriate_adult__": [ { "__kind__": "Person", "born": "1980-05-25T00:00:00", "first_name": "Bob", ... "userid": 3 } ] } ] }, { "__kind__": "Person", "born": "1999-09-19T00:00:00", "first_name": "Alice", ... "__children__appropriate_adult__": [ { "__kind__": "Person", ... "__children__owner__": [ { "__kind__": "Dog", "name": "Fido" } ] } ] } ] you can reconstruct entire entity trees for your tests. Parent/Ancestor-based relationships with automatic keys ------------------------------------------------------- It's also possible to set the `parent` by using the `__children__` attribute. For our example classes, importing: .. code-block:: javascript [ { "__kind__": "Person", "first_name": "Alice", ... "__children__": [ { "__kind__": "Person", "first_name": "Bob", ... "__children__owner__": [ { "__kind__": "Dog", "name": "Fido" } ] } ] } ] should be equivalent to: .. code-block:: python alice = Person(first_name='Alice') alice.put() bob = Person(first_name='Bob', parent=alice) bob.put() fido = Dog(name='Fido', parent=bob) fido.put() You can then retrieve fido with: .. code-block:: python fido = Dog.query(ancestor=alice.key).get() Development =========== There are two recommended ways to work on this codebase. If you want to keep one and only one App Engine SDK install, you may clone the repository and run the tests by:: $ PYTHONPATH=path/to/appengine/library python setup.py test Alternatively, this project contains code and support files derived from the testable_appengine project. Testable_appengine was conceived to make it easier to write (and run) tests for Google App Engine applications and to hook your application to Travis CI. In essence, it creates a virtualenv and downloads the most up-to-date SDK and other support tools into it. To use it, you run `make`. Calling `make help` will give you a quick list of available make targets:: $ make venv Running virtualenv with interpreter /usr/bin/python2 New python executable in /export/home/ricardo/projects/appengine-fixture-loader/.env/bin/python2 Also creating executable in /export/home/ricardo/projects/appengine-fixture-loader/.env/bin/python (...) ‘/export/home/ricardo/projects/appengine-fixture-loader/.env/bin/run_tests.py’ -> ‘/export/home/ricardo/projects/appengine-fixture-loader/.env/lib/google_appengine/run_tests.py’ ‘/export/home/ricardo/projects/appengine-fixture-loader/.env/bin/wrapper_util.py’ -> ‘/export/home/ricardo/projects/appengine-fixture-loader/.env/lib/google_appengine/wrapper_util.py’ $ source .env/bin/activate (.env) $ nosetests .............. ---------------------------------------------------------------------- Ran 14 tests in 2.708s OK
Appengine-Fixture-Loader
/Appengine-Fixture-Loader-0.1.9.tar.gz/Appengine-Fixture-Loader-0.1.9/README.rst
README.rst
============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Types of Contributions ---------------------- Report Bugs ~~~~~~~~~~~ Report bugs at https://github.com/rbanffy/appengine-fixture-loader/issues. If you are reporting a bug, please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Fix Bugs ~~~~~~~~ Look through the GitHub issues for bugs. Anything tagged with "bug" is open to whoever wants to implement it. Implement Features ~~~~~~~~~~~~~~~~~~ Look through the GitHub issues for features. Anything tagged with "feature" is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ App Engine Fixture Loader could always use more documentation, whether as part of the official App Engine Fixture Loader docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ The best way to send feedback is to file an issue at https://github.com/rbanffy/appengine-fixture-loader/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ------------ Ready to contribute? Here's how to set up `appengine-fixture-loader` for local development. 1. Fork the `appengine-fixture-loader` repo on GitHub. 2. Clone your fork locally:: $ git clone [email protected]:your_name_here/appengine-fixture-loader.git 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: $ mkvirtualenv appengine-fixture-loader $ cd appengine-fixture-loader/ $ python setup.py develop 4. Create a branch for local development:: $ git checkout -b name-of-your-bugfix-or-feature Now you can make your changes locally. 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ flake8 appengine-fixture-loader tests $ python setup.py test $ tox To get flake8 and tox, just pip install them into your virtualenv. 6. Commit your changes and push your branch to GitHub:: $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature 7. Submit a pull request through the GitHub website. Pull Request Guidelines ----------------------- Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. 3. The pull request should work for Python 2.6, 2.7, 3.3, and 3.4, and for PyPy. Check https://travis-ci.org/rbanffy/appengine-fixture-loader/pull_requests and make sure that the tests pass for all supported Python versions. Tips ---- To run a subset of tests:: $ python -m unittest tests.test_appengine-fixture-loader
Appengine-Fixture-Loader
/Appengine-Fixture-Loader-0.1.9.tar.gz/Appengine-Fixture-Loader-0.1.9/CONTRIBUTING.rst
CONTRIBUTING.rst
.. appengine_fixture_loader documentation master file, created by sphinx-quickstart on Tue Jul 9 22:26:36 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to App Engine Fixture Loader's documentation! ====================================== Contents: .. toctree:: :maxdepth: 2 readme installation usage contributing authors history Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
Appengine-Fixture-Loader
/Appengine-Fixture-Loader-0.1.9.tar.gz/Appengine-Fixture-Loader-0.1.9/docs/index.rst
index.rst
import json from datetime import datetime, time, date from google.appengine.ext.ndb.model import (DateTimeProperty, DateProperty, TimeProperty) def _sensible_value(attribute_type, value): if type(attribute_type) is DateTimeProperty: retval = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S') elif type(attribute_type) is TimeProperty: try: dt = datetime.strptime(value, '%H:%M:%S') except ValueError: dt = datetime.strptime(value, '%H:%M') retval = time(dt.hour, dt.minute, dt.second) elif type(attribute_type) is DateProperty: dt = datetime.strptime(value, '%Y-%m-%d') retval = date(dt.year, dt.month, dt.day) else: retval = value return retval def load_fixture(filename, kind, post_processor=None): """ Loads a file into entities of a given class, run the post_processor on each instance before it's saved """ def _load(od, kind, post_processor, parent=None, presets={}): """ Loads a single dictionary (od) into an object, overlays the values in presets, persists it and calls itself on the objects in __children__* keys """ if hasattr(kind, 'keys'): # kind is a map objtype = kind[od['__kind__']] else: objtype = kind obj_id = od.get('__id__') if obj_id is not None: obj = objtype(id=obj_id, parent=parent) else: obj = objtype(parent=parent) # Iterate over the non-special attributes and overlay the presets for attribute_name in [k for k in od.keys() if not k.startswith('__') and not k.endswith('__')] + presets.keys(): attribute_type = objtype.__dict__[attribute_name] attribute_value = _sensible_value(attribute_type, presets.get( attribute_name, od.get(attribute_name))) obj.__dict__['_values'][attribute_name] = attribute_value if post_processor: post_processor(obj) # Saving obj is required to continue with the children obj.put() loaded = [obj] # Process ancestor-based __children__ for item in od.get('__children__', []): loaded.extend(_load(item, kind, post_processor, parent=obj.key)) # Process other __children__[key]__ items for child_attribute_name in [k for k in od.keys() if k.startswith('__children__') and k != '__children__']: attribute_name = child_attribute_name.split('__')[-2] for child in od[child_attribute_name]: loaded.extend(_load(child, kind, post_processor, presets={attribute_name: obj.key})) return loaded tree = json.load(open(filename)) loaded = [] # Start with the top-level of the tree for item in tree: loaded.extend(_load(item, kind, post_processor)) return loaded
Appengine-Fixture-Loader
/Appengine-Fixture-Loader-0.1.9.tar.gz/Appengine-Fixture-Loader-0.1.9/appengine_fixture_loader/loader.py
loader.py
hello my name is parsa mehrabi this is for creat application window for all os install: |-----------------| |pip install Apper| |-----------------| create window: from Apper import * PC.setting(title='Apper',bground='red',width=500,height=500,icon=f'C:/Users/Parsa/Desktop/icon.ico') PC.run() create button: PC.button(text='Apper',bground=None,textvar=None,fground='black',width=10,height=2,x=0,y=0) and all codes and widgets...... okay! please learn other codes in http://jupiter-pl.epizy.com
Apper
/Apper-0.0.2.tar.gz/Apper-0.0.2/README.md
README.md
# Getting the Appium Flutter Finder There are three ways to install and use the Appium Flutter Finder. Supported Python version follows appium python client. 1. Install from [PyPi](https://pypi.org), as ['Appium-Flutter-Finder'](https://pypi.org/project/Appium-Flutter-Finder/). ```shell pip install Appium-Flutter-Finder ``` 2. Install from source, via [PyPi](https://pypi.org). From ['Appium-Flutter-Finder'](https://pypi.org/project/Appium-Flutter-Finder/), download and unarchive the source tarball (Appium-Flutter-Finder-X.X.tar.gz). ```shell tar -xvf Appium-Flutter-Finder-X.X.tar.gz cd Appium-Flutter-Finder-X.X python setup.py install ``` 3. Install from source via [GitHub](https://github.com/appium/python-client). ```shell git clone [email protected]:appium/python-client.git cd python-client python setup.py install ``` # How to use Examples can be found out [here](../../example/python/example.py). # Release ``` pip install twine ``` ``` python setup.py sdist twine upload dist/Appium-Flutter-Finder-X.X.tar.gz ``` # Changelog - 0.4.0 - Bump base Appium-Python-Client to v2 - 0.3.1 - Use Appium-Python-Client 1.x - 0.3.0 - Add `first_match_only` option in `by_ancestor` and `by_descendant` - 0.2.0 - Support over Python 3.6 - 0.1.5 - Fix `by_ancestor` and `by_descendant` - https://github.com/truongsinh/appium-flutter-driver/pull/165#issuecomment-877928553 - 0.1.4 - Remove whitespaces from the decoded JSON - Fix `by_ancestor` and `by_descendant` - 0.1.3 - Allow `from appium_flutter_finder import FlutterElement, FlutterFinder` - 0.1.2 - Fix b64encode error in Python 3 - 0.1.1 - Initial release
Appium-Flutter-Finder
/Appium-Flutter-Finder-0.4.0.tar.gz/Appium-Flutter-Finder-0.4.0/README.md
README.md
import base64 import json from appium.webdriver.webelement import WebElement class FlutterElement(WebElement): pass class FlutterFinder: def by_ancestor(self, serialized_finder, matching, match_root=False, first_match_only=False): return self._by_ancestor_or_descendant( type_='Ancestor', serialized_finder=serialized_finder, matching=matching, match_root=match_root, first_match_only=first_match_only ) def by_descendant(self, serialized_finder, matching, match_root=False, first_match_only=False): return self._by_ancestor_or_descendant( type_='Descendant', serialized_finder=serialized_finder, matching=matching, match_root=match_root, first_match_only=first_match_only ) def by_semantics_label(self, label, isRegExp=False): return self._serialize(dict( finderType='BySemanticsLabel', isRegExp=isRegExp, label=label )) def by_tooltip(self, text): return self._serialize(dict( finderType='ByTooltipMessage', text=text )) def by_text(self, text): return self._serialize(dict( finderType='ByText', text=text )) def by_type(self, type_): return self._serialize(dict( finderType='ByType', type=type_ )) def by_value_key(self, key): return self._serialize(dict( finderType='ByValueKey', keyValueString=key, keyValueType='String' if isinstance(key, str) else 'int' )) def page_back(self): return self._serialize(dict( finderType='PageBack' )) def _serialize(self, finder_dict): return base64.b64encode( bytes(json.dumps(finder_dict, separators=(',', ':')), 'UTF-8')).decode('UTF-8') def _by_ancestor_or_descendant(self, type_, serialized_finder, matching, match_root=False, first_match_only=False): param = dict(finderType=type_, matchRoot=match_root, firstMatchOnly=first_match_only) try: finder = json.loads(base64.b64decode( serialized_finder).decode('utf-8')) except Exception: finder = {} param.setdefault('of', {}) for finder_key, finder_value in finder.items(): param['of'].setdefault(finder_key, finder_value) param['of'] = json.dumps(param['of'], separators=(',', ':')) try: matching = json.loads(base64.b64decode(matching).decode('utf-8')) except Exception: matching = {} param.setdefault('matching', {}) for matching_key, matching_value in matching.items(): param['matching'].setdefault(matching_key, matching_value) param['matching'] = json.dumps(param['matching'], separators=(',', ':')) return self._serialize(param)
Appium-Flutter-Finder
/Appium-Flutter-Finder-0.4.0.tar.gz/Appium-Flutter-Finder-0.4.0/appium_flutter_finder/flutter_finder.py
flutter_finder.py
# Appium Python Client Moneky Hot Patch For [Appium-Python-Client](https://github.com/appium/python-client) [![PyPI version](https://badge.fury.io/py/Appium-Python-Client-Monkey.svg)](https://badge.fury.io/py/Appium-Python-Client-Monkey) [![Downloads](https://pepy.tech/badge/appium-python-client-monkey)](https://pepy.tech/project/appium-python-client-monkey) An extension library for adding [WebDriver Protocol](https://www.w3.org/TR/webdriver/) and Appium commands to the Selenium Python language binding for use with the mobile testing framework [Appium](https://appium.io). ## Notice Since Appium_Python-Client **v1.0.0**, only Python 3.7+ is supported. Since Appium_Python-Client **v2.0.0**, the base selenium client version is v4. The version only works in W3C WebDriver protocol format. If you would like to use the old protocol (MJSONWP), please use v1 Appium Python client. [More Reference](https://github.com/appium/python-client) ## Getting the Appium Python client Monkey There are three ways to install and use the Appium Python client. 1. Install from [PyPi](https://pypi.org), as ['Appium-Python-Client-Monkey'](https://pypi.org/project/Appium-Python-Client-Monkey/). ```shell pip install Appium-Python-Client-Monkey ``` You can see the history from [here](https://pypi.org/project/Appium-Python-Client-Mokey/#history) 2. Install from source, via [PyPi](https://pypi.org). From ['Appium-Python-Client'](https://pypi.org/project/Appium-Python-Client-Monkey/), download and unarchive the source tarball (Appium-Python-Client-Monkey-X.X.tar.gz). ```shell tar -xvf Appium-Python-Client-Monkey-X.X.tar.gz cd Appium-Python-Client-Monkey-X.X python setup.py install ``` 3. Install from source via [GitHub](https://github.com/CN-Robert-LIU/appium-python-client-monkey). ```shell git clone [email protected]:CN-Robert-LIU/appium-python-client-monkey.git cd appium-python-client-monkey python setup.py install ``` ## Usage The Appium Python Client is fully compliant with the WebDriver Protocol including several helpers to make mobile testing in Python easier. To use the new functionality now, and to use the superset of functions, instead of including the Selenium `webdriver` module in your test code, use that from Appium instead. ```python from appium import webdriver from appium_patch import monkey webdriver.Remote = monkey.patch_all() ``` From there much of your test code will work with no change. As a base for the following code examples, the following sets up the [UnitTest](https://docs.python.org/3/library/unittest.html) environment: ```python # Android environment import unittest from appium import webdriver from appium_patch import monkey webdriver.Remote = monkey.patch_all() desired_caps = dict( platformName='Android', platformVersion='10', automationName='uiautomator2', deviceName='Android Emulator', app=PATH('../../../apps/selendroid-test-app.apk') ) self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) el = self.driver.find_element_by_accessibility_id('item') el.click() ``` ```python # iOS environment import unittest from appium import webdriver from appium_patch import monkey webdriver.Remote = monkey.patch_all() desired_caps = dict( platformName='iOS', platformVersion='13.4', automationName='xcuitest', deviceName='iPhone Simulator', app=PATH('../../apps/UICatalog.app.zip') ) self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) el = self.driver.find_element_by_accessibility_id('item') el.click() ``` ## Direct Connect URLs If your Selenium/Appium server decorates the new session capabilities response with the following keys: - `directConnectProtocol` - `directConnectHost` - `directConnectPort` - `directConnectPath` Then python client will switch its endpoint to the one specified by the values of those keys. ```python import unittest from appium import webdriver from appium_patch import monkey webdriver.Remote = monkey.patch_all() desired_caps = dict( platformName='iOS', platformVersion='13.4', automationName='xcuitest', deviceName='iPhone Simulator', app=PATH('../../apps/UICatalog.app.zip') ) self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps, direct_connection=True) ``` ## Relax SSL validation `strict_ssl` option allows you to send commands to an invalid certificate host like a self-signed one. ```python import unittest from appium import webdriver from appium_patch import monkey webdriver.Remote = monkey.patch_all() desired_caps = dict( platformName='iOS', platformVersion='13.4', automationName='xcuitest', deviceName='iPhone Simulator', app=PATH('../../apps/UICatalog.app.zip') ) self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps, strict_ssl=False) ``` ## License Apache License v2
Appium-Python-Client-Monkey
/Appium-Python-Client-Monkey-1.0.0.tar.gz/Appium-Python-Client-Monkey-1.0.0/README.md
README.md
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Author: CN-Robert-LIU # Date: 2021-12-02 # Version: V1.0.0 # Description: Patch And Enhance Appium-Python-API from appium.webdriver.webdriver import WebDriver from appium.webdriver.common.appiumby import AppiumBy from appium.webdriver import WebElement as MobileWebElement from typing import List, Union __all__ = [ 'patch_find_element_by_id', 'patch_find_elements_by_id', 'patch_find_element_by_xpath', 'patch_find_elements_by_xpath', 'patch_find_element_by_link_text', 'patch_find_elements_by_link_text', 'patch_find_element_by_partial_link_text', 'patch_find_elements_by_partial_link_text', 'patch_find_element_by_name', 'patch_find_elements_by_name', 'patch_find_element_by_tag_name', 'patch_find_elements_by_tag_name', 'patch_find_element_by_class_name', 'patch_find_elements_by_class_name', 'patch_find_element_by_css_selector', 'patch_find_elements_by_css_selector', 'patch_swipe_ios_up', 'patch_swipe_ios_down', 'patch_swipe_ios_left', 'patch_swipe_ios_right' ] def patch_find_element_by_id(self, id_: str) -> MobileWebElement: """ Finds an element by id. :Args: - id\\_ - The id of the element to be found. :Returns: - `appium.webdriver.webelement.WebElement`: The found element :Raises: - NoSuchElementException - if the element wasn't found :Usage: :: element = driver.find_element_by_id('foo') """ return self.find_element(by=AppiumBy.ID, value=id_) def patch_find_elements_by_id(self, id_: str) -> Union[List[MobileWebElement], List]: """ Finds multiple elements by id. :Args: - id\\_ - The id of the elements to be found. :Returns: - :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements empty list if not :Usage: :: elements = driver.find_elements_by_id('foo') """ return self.find_elements(by=AppiumBy.ID, value=id_) def patch_find_element_by_xpath(self, xpath: str) -> MobileWebElement: """ Finds an element by xpath. :Args: - xpath - The xpath locator of the element to find. :Returns: - `appium.webdriver.webelement.WebElement`: The found element :Raises: - NoSuchElementException - if the element wasn't found :Usage: :: element = driver.find_element_by_xpath('//div/td[1]') """ return self.find_element(by=AppiumBy.XPATH, value=xpath) def patch_find_elements_by_xpath(self, xpath: str) -> Union[List[MobileWebElement], List]: """ Finds multiple elements by xpath. :Args: - xpath - The xpath locator of the elements to be found. :Returns: - :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements empty list if not :Usage: :: elements = driver.find_elements_by_xpath( "//div[contains(@class, 'foo')]") """ return self.find_elements(by=AppiumBy.XPATH, value=xpath) def patch_find_element_by_link_text(self, link_text: str) -> MobileWebElement: """ Finds an element by link text. :Args: - link_text: The text of the element to be found. :Returns: - `appium.webdriver.webelement.WebElement`: The found element :Raises: - NoSuchElementException - if the element wasn't found :Usage: :: element = driver.find_element_by_link_text('Sign In') """ return self.find_element(by=AppiumBy.LINK_TEXT, value=link_text) def patch_find_elements_by_link_text(self, text: str) -> Union[List[MobileWebElement], List]: """ Finds elements by link text. :Args: - link_text: The text of the elements to be found. :Returns: - :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements empty list if not :Usage: :: elements = driver.find_elements_by_link_text('Sign In') """ return self.find_elements(by=AppiumBy.LINK_TEXT, value=text) def patch_find_element_by_partial_link_text(self, link_text: str) -> MobileWebElement: """ Finds an element by a partial match of its link text. :Args: - link_text: The text of the element to partially match on. :Returns: - `appium.webdriver.webelement.WebElement`: The found element :Raises: - NoSuchElementException - if the element wasn't found :Usage: :: element = driver.find_element_by_partial_link_text('Sign') """ return self.find_element(by=AppiumBy.PARTIAL_LINK_TEXT, value=link_text) def patch_find_elements_by_partial_link_text(self, link_text: str) -> Union[List[MobileWebElement], List]: """ Finds elements by a partial match of their link text. :Args: - link_text: The text of the element to partial match on. :Returns: - :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements empty list if not :Usage: :: elements = driver.find_elements_by_partial_link_text('Sign') """ return self.find_elements(by=AppiumBy.PARTIAL_LINK_TEXT, value=link_text) def patch_find_element_by_name(self, name: str) -> MobileWebElement: """ Finds an element by name. :Args: - name: The name of the element to find. :Returns: - `appium.webdriver.webelement.WebElement`: The found element :Raises: - NoSuchElementException - if the element wasn't found :Usage: :: element = driver.find_element_by_name('foo') """ return self.find_element(by=AppiumBy.NAME, value=name) def patch_find_elements_by_name(self, name: str) -> Union[List[MobileWebElement], List]: """ Finds elements by name. :Args: - name: The name of the elements to find. :Returns: - :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements empty list if not :Usage: :: elements = driver.find_elements_by_name('foo') """ return self.find_elements(by=AppiumBy.NAME, value=name) def patch_find_element_by_tag_name(self, name: str) -> MobileWebElement: """ Finds an element by tag name. :Args: - name - name of html tag (eg: h1, a, span) :Returns: - `appium.webdriver.webelement.WebElement`: The found element :Raises: - NoSuchElementException - if the element wasn't found :Usage: :: element = driver.find_element_by_tag_name('h1') """ return self.find_element(by=AppiumBy.TAG_NAME, value=name) def patch_find_elements_by_tag_name(self, name: str) -> Union[List[MobileWebElement], List]: """ Finds elements by tag name. :Args: - name - name of html tag (eg: h1, a, span) :Returns: - :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements empty list if not :Usage: :: elements = driver.find_elements_by_tag_name('h1') """ return self.find_elements(by=AppiumBy.TAG_NAME, value=name) def patch_find_element_by_class_name(self, name: str) -> MobileWebElement: """ Finds an element by class name. :Args: - name: The class name of the element to find. :Returns: - `appium.webdriver.webelement.WebElement`: The found element :Raises: - NoSuchElementException - if the element wasn't found :Usage: :: element = driver.find_element_by_class_name('foo') """ return self.find_element(by=AppiumBy.CLASS_NAME, value=name) def patch_find_elements_by_class_name(self, name: str) -> Union[List[MobileWebElement], List]: """ Finds elements by class name. :Args: - name: The class name of the elements to find. :Returns: - :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements empty list if not :Usage: :: elements = driver.find_elements_by_class_name('foo') """ return self.find_elements(by=AppiumBy.CLASS_NAME, value=name) def patch_find_element_by_css_selector(self, css_selector: str) -> MobileWebElement: """ Finds an element by css selector. :Args: - css_selector - CSS selector string, ex: 'a.nav#home' :Returns: - `appium.webdriver.webelement.WebElement`: The found element :Raises: - NoSuchElementException - if the element wasn't found :Usage: :: element = driver.find_element_by_css_selector('#foo') """ return self.find_element(by=AppiumBy.CSS_SELECTOR, value=css_selector) def patch_find_elements_by_css_selector(self, css_selector: str) -> Union[List[MobileWebElement], List]: """ Finds elements by css selector. :Args: - css_selector - CSS selector string, ex: 'a.nav#home' :Returns: - :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements empty list if not :Usage: :: elements = driver.find_elements_by_css_selector('.foo') """ return self.find_elements(by=AppiumBy.CSS_SELECTOR, value=css_selector) def patch_swipe_ios_up(self, duration: int = 0): """ Swipe Up For IOS Mobile. :Returns: - :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements empty list if not :Usage: :: driver.swipe_ios_up() """ import time self.execute_script("mobile:swipe", {"direction": "up"}) if duration: time.sleep(duration) def patch_swipe_ios_down(self, duration: int = 0): """ Swipe Down For IOS Mobile. :Usage: :: driver.swipe_ios_down() """ import time self.execute_script("mobile:swipe", {"direction": "down"}) if duration: time.sleep(duration) def patch_swipe_ios_left(self, duration: int = 0): """ Swipe LEFT For IOS Mobile. :Usage: :: driver.swipe_ios_left() """ import time self.execute_script("mobile:swipe", {"direction": "left"}) if duration: time.sleep(duration) def patch_swipe_ios_right(self, duration: int = 0): """ Swipe Up For IOS Mobile. :Usage: :: driver.swipe_ios_right() """ import time self.execute_script("mobile:swipe", {"direction": "right"}) if duration: time.sleep(duration) def patch_all(): """ Do all of the default monkey patching (calls every other applicable function in this module). :return: appium.webdriver.WebDriver as Remote """ # from .webdriver import WebDriver as Remote from appium.webdriver.webdriver import WebDriver # Update Hot Pacth To webdriver API WebDriver.find_element_by_id = patch_find_element_by_id WebDriver.find_elements_by_id = patch_find_elements_by_id WebDriver.find_element_by_xpath = patch_find_element_by_xpath WebDriver.find_elements_by_xpath = patch_find_elements_by_xpath WebDriver.find_element_by_link_text = patch_find_element_by_link_text WebDriver.find_elements_by_link_text = patch_find_elements_by_link_text WebDriver.find_element_by_partial_link_text = patch_find_element_by_partial_link_text WebDriver.find_elements_by_partial_link_text = patch_find_elements_by_partial_link_text WebDriver.find_element_by_name = patch_find_element_by_name WebDriver.find_elements_by_name = patch_find_elements_by_name WebDriver.find_element_by_tag_name = patch_find_element_by_tag_name WebDriver.find_elements_by_tag_name = patch_find_elements_by_tag_name WebDriver.find_element_by_class_name = patch_find_element_by_class_name WebDriver.find_elements_by_class_name = patch_find_elements_by_class_name WebDriver.find_element_by_css_selector = patch_find_element_by_css_selector WebDriver.find_elements_by_css_selector = patch_find_elements_by_css_selector WebDriver.swipe_ios_up = patch_swipe_ios_up WebDriver.swipe_ios_down = patch_swipe_ios_down WebDriver.swipe_ios_left = patch_swipe_ios_left WebDriver.swipe_ios_right = patch_swipe_ios_right Remote = WebDriver return Remote
Appium-Python-Client-Monkey
/Appium-Python-Client-Monkey-1.0.0.tar.gz/Appium-Python-Client-Monkey-1.0.0/appium_patch/monkey.py
monkey.py
# Appium Python Client [![PyPI version](https://badge.fury.io/py/Appium-Python-Client.svg)](https://badge.fury.io/py/Appium-Python-Client) [![Downloads](https://pepy.tech/badge/appium-python-client)](https://pepy.tech/project/appium-python-client) [![Build Status](https://dev.azure.com/AppiumCI/Appium%20CI/_apis/build/status/appium.python-client?branchName=master)](https://dev.azure.com/AppiumCI/Appium%20CI/_build/latest?definitionId=56&branchName=master) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) An extension library for adding [WebDriver Protocol](https://www.w3.org/TR/webdriver/) and Appium commands to the Selenium Python language binding for use with the mobile testing framework [Appium](https://appium.io). ## Notice Since **v1.0.0**, only Python 3.7+ is supported. Since **v2.0.0**, the base selenium client version is v4. The version only works in W3C WebDriver protocol format. If you would like to use the old protocol (MJSONWP), please use v1 Appium Python client. ### Quick migration guide from v1 to v2 - Enhancement - Updated base Selenium Python binding version to v4 - Removed `forceMjsonwp` since Selenium v4 and Appium Python client v2 expect only W3C WebDriver protocol - Methods `ActionHelpers#scroll`, `ActionHelpers#drag_and_drop`, `ActionHelpers#tap`, `ActionHelpers#swipe` and `ActionHelpers#flick` now call W3C actions as its backend - Please check each behavior. Their behaviors could slightly differ. - Added `strict_ssl` to relax SSL error such as self-signed ones - Deprecated - `MultiAction` and `TouchAction` are deprecated. Please use W3C WebDriver actions. - e.g. - [appium/webdriver/extensions/action_helpers.py](appium/webdriver/extensions/action_helpers.py) - https://www.selenium.dev/documentation/support_packages/mouse_and_keyboard_actions_in_detail/ - https://www.youtube.com/watch?v=oAJ7jwMNFVU - https://appiumpro.com/editions/30-ios-specific-touch-action-methods - https://appiumpro.com/editions/29-automating-complex-gestures-with-the-w3c-actions-api - `launch_app`, `close_app` and `reset` are deprecated. Please read [issues#15807](https://github.com/appium/appium/issues/15807) for more details #### MultiAction/TouchAction to W3C actions On UIA2, some elements can be handled with `touch` pointer action insead of the default `mouse` pointer action in the Selenium Python cleint. For example, the below action builder is to replace the default one with the `touch` pointer action. ```python from selenium.webdriver.common.actions import interaction from selenium.webdriver.common.actions.action_builder import ActionBuilder actions = ActionChains(driver) # override as 'touch' pointer action actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch")) actions.w3c_actions.pointer_action.move_to_location(start_x, start_y) actions.w3c_actions.pointer_action.pointer_down() actions.w3c_actions.pointer_action.pause(2) actions.w3c_actions.pointer_action.move_to_location(end_x, end_y) actions.w3c_actions.pointer_action.release() actions.perform() ``` ## Getting the Appium Python client There are three ways to install and use the Appium Python client. 1. Install from [PyPi](https://pypi.org), as ['Appium-Python-Client'](https://pypi.org/project/Appium-Python-Client/). ```shell pip install Appium-Python-Client ``` You can see the history from [here](https://pypi.org/project/Appium-Python-Client/#history) 2. Install from source, via [PyPi](https://pypi.org). From ['Appium-Python-Client'](https://pypi.org/project/Appium-Python-Client/), download and unarchive the source tarball (Appium-Python-Client-X.X.tar.gz). ```shell tar -xvf Appium-Python-Client-X.X.tar.gz cd Appium-Python-Client-X.X python setup.py install ``` 3. Install from source via [GitHub](https://github.com/appium/python-client). ```shell git clone [email protected]:appium/python-client.git cd python-client python setup.py install ``` ## Compatibility Matrix |Appium Python Client| Selenium binding| |----|----| |`2.10.0`+ |`4.1.0`+ | |`2.2.0` - `2.9.0` |`4.1.0` - `4.9.0` | |`2.0.0` - `2.1.4` |`4.0.0` | |`1.1.0` and below|`3.x`| The Appium Python Client depends on [Selenium Python binding](https://pypi.org/project/selenium/), thus the Selenium Python binding update might affect the Appium Python Client behavior. For exampple, some changes in the Selenium binding could break the Appium client. > **Note** > We strongly recommend you to manage dependencies with version management tools such as Pipenv and requirements.txt > to keep compatible version combinations. ## Usage The Appium Python Client is fully compliant with the WebDriver Protocol including several helpers to make mobile testing in Python easier. To use the new functionality now, and to use the superset of functions, instead of including the Selenium `webdriver` module in your test code, use that from Appium instead. ```python from appium import webdriver ``` From there much of your test code will work with no change. As a base for the following code examples, the following sets up the [UnitTest](https://docs.python.org/3/library/unittest.html) environment: ```python # Python/Pytest import pytest from appium import webdriver # Options are only available since client version 2.3.0 # If you use an older client then switch to desired_capabilities # instead: https://github.com/appium/python-client/pull/720 from appium.options.android import UiAutomator2Options from appium.options.ios import XCUITestOptions from appium.webdriver.appium_service import AppiumService from appium.webdriver.common.appiumby import AppiumBy APPIUM_PORT = 4723 APPIUM_HOST = '127.0.0.1' # HINT: fixtures below could be extracted into conftest.py # HINT: and shared across all tests in the suite @pytest.fixture(scope='session') def appium_service(): service = AppiumService() service.start( # Check the output of `appium server --help` for the complete list of # server command line arguments args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT)], timeout_ms=20000, ) yield service service.stop() def create_ios_driver(custom_opts = None): options = XCUITestOptions() options.platformVersion = '13.4' options.udid = '123456789ABC' if custom_opts is not None: options.load_capabilities(custom_opts) # Appium1 points to http://127.0.0.1:4723/wd/hub by default return webdriver.Remote(f'http://{APPIUM_HOST}:{APPIUM_PORT}', options=options) def create_android_driver(custom_opts = None): options = UiAutomator2Options() options.platformVersion = '10' options.udid = '123456789ABC' if custom_opts is not None: options.load_capabilities(custom_opts) # Appium1 points to http://127.0.0.1:4723/wd/hub by default return webdriver.Remote(f'http://{APPIUM_HOST}:{APPIUM_PORT}', options=options) @pytest.fixture def ios_driver_factory(): return create_ios_driver @pytest.fixture def ios_driver(): # prefer this fixture if there is no need to customize driver options in tests driver = create_ios_driver() yield driver driver.quit() @pytest.fixture def android_driver_factory(): return create_android_driver @pytest.fixture def android_driver(): # prefer this fixture if there is no need to customize driver options in tests driver = create_android_driver() yield driver driver.quit() def test_ios_click(appium_service, ios_driver_factory): # Usage of the context manager ensures the driver session is closed properly # after the test completes. Otherwise, make sure to call `driver.quit()` on teardown. with ios_driver_factory({ 'appium:app': '/path/to/app/UICatalog.app.zip' }) as driver: el = driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value='item') el.click() def test_android_click(appium_service, android_driver_factory): # Usage of the context manager ensures the driver session is closed properly # after the test completes. Otherwise, make sure to call `driver.quit()` on teardown. with android_driver_factory({ 'appium:app': '/path/to/app/test-app.apk', 'appium:udid': '567890', }) as driver: el = driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value='item') el.click() ``` ## Direct Connect URLs If your Selenium/Appium server decorates the new session capabilities response with the following keys: - `directConnectProtocol` - `directConnectHost` - `directConnectPort` - `directConnectPath` Then python client will switch its endpoint to the one specified by the values of those keys. ```python from appium import webdriver # Options are only available since client version 2.3.0 # If you use an older client then switch to desired_capabilities # instead: https://github.com/appium/python-client/pull/720 from appium.options.ios import XCUITestOptions # load_capabilities API could be used to # load options mapping stored in a dictionary options = XCUITestOptions().load_capabilities({ 'platformVersion': '13.4', 'deviceName': 'iPhone Simulator', 'app': '/full/path/to/app/UICatalog.app.zip', }) driver = webdriver.Remote( # Appium1 points to http://127.0.0.1:4723/wd/hub by default 'http://127.0.0.1:4723', options=options, direct_connection=True ) ``` ## Relax SSL validation `strict_ssl` option allows you to send commands to an invalid certificate host like a self-signed one. ```python from appium import webdriver # Options are only available since client version 2.3.0 # If you use an older client then switch to desired_capabilities # instead: https://github.com/appium/python-client/pull/720 from appium.options.common import AppiumOptions options = AppiumOptions() options.platform_name = 'mac' options.automation_name = 'safari' # set_capability API allows to provide any custom option # calls to it could be chained options.set_capability('browser_name', 'safari') # Appium1 points to http://127.0.0.1:4723/wd/hub by default driver = webdriver.Remote('http://127.0.0.1:4723', options=options, strict_ssl=False) ``` ## Set custom `AppiumConnection` The first argument of `webdriver.Remote` can set an arbitrary command executor for you. 1. Set init arguments for the pool manager Appium Python client uses to manage http requests. ```python from appium import webdriver from appium.options.ios import XCUITestOptions import urllib3 from appium.webdriver.appium_connection import AppiumConnection # Retry connection error up to 3 times. init_args_for_pool_manage = { 'retries': urllib3.util.retry.Retry(total=3, connect=3, read=False) } appium_executor = AppiumConnection( remote_server_addr='http://127.0.0.1:4723', init_args_for_pool_manage=init_args_for_pool_manage ) options = XCUITestOptions() options.platformVersion = '13.4' options.udid = '123456789ABC' options.app = '/full/path/to/app/UICatalog.app.zip' driver = webdriver.Remote(appium_executor, options=options) ``` 2. Define a subclass of `AppiumConnection` ```python from appium import webdriver from appium.options.ios import XCUITestOptions from appium.webdriver.appium_connection import AppiumConnection class CustomAppiumConnection(AppiumConnection): # Can add your own methods for the custom class pass custom_executor = CustomAppiumConnection(remote_server_addr='http://127.0.0.1:4723') options = XCUITestOptions().load_capabilities({ 'platformVersion': '13.4', 'deviceName': 'iPhone Simulator', 'app': '/full/path/to/app/UICatalog.app.zip', }) driver = webdriver.Remote(custom_executor, options=options) ``` ## Documentation - https://appium.github.io/python-client-sphinx/ is detailed documentation - [functional tests](test/functional) also may help to see concrete examples. ## Development - Code Style: [PEP-0008](https://www.python.org/dev/peps/pep-0008/) - Apply `black`, `isort` and `mypy` as pre commit hook - Run `make` command for development. See `make help` output for details - Docstring style: [Google Style](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) - `gitchangelog` generates `CHANGELOG.rst` ### Setup - `pip install --user pipenv` - `python -m pipenv lock --clear` - If you experience `Locking Failed! unknown locale: UTF-8` error, then refer [pypa/pipenv#187](https://github.com/pypa/pipenv/issues/187) to solve it. - `python -m pipenv install --dev --system` - `pre-commit install` ### Run tests You can run all of tests running on CI via `tox` in your local. ```bash $ tox ``` You also can run particular tests like below. #### Unit ```bash $ pytest test/unit ``` Run with `pytest-xdist` ```bash $ pytest -n 2 test/unit ``` #### Functional ```bash $ pytest test/functional/ios/search_context/find_by_ios_class_chain_tests.py ``` #### In parallel for iOS 1. Create simulators named 'iPhone X - 8100' and 'iPhone X - 8101' 2. Install test libraries via pip, `pip install pytest pytest-xdist` 3. Run tests ```bash $ pytest -n 2 test/functional/ios/search_context/find_by_ios_class_chain_tests.py ``` ## Release Follow below steps. ```bash $ pip install twine $ pip install git+git://github.com/vaab/gitchangelog.git # Getting via GitHub repository is necessary for Python 3.7 # Type the new version number and 'yes' if you can publish it # You can test the command with DRY_RUN $ DRY_RUN=1 ./release.sh $ ./release.sh # release ``` ## License Apache License v2
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/README.md
README.md
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import re import subprocess as sp import sys import time from typing import Any, List, Optional, Set from selenium.webdriver.remote.remote_connection import urllib3 DEFAULT_HOST = '127.0.0.1' DEFAULT_PORT = 4723 STARTUP_TIMEOUT_MS = 60000 MAIN_SCRIPT_PATH = 'appium/build/lib/main.js' STATUS_URL = '/status' DEFAULT_BASE_PATH = '/' class AppiumServiceError(RuntimeError): pass class AppiumStartupError(RuntimeError): pass def find_executable(executable: str) -> Optional[str]: path = os.environ['PATH'] paths = path.split(os.pathsep) _, ext = os.path.splitext(executable) if sys.platform == 'win32' and not ext: executable = executable + '.exe' if os.path.isfile(executable): return executable for p in paths: full_path = os.path.join(p, executable) if os.path.isfile(full_path): return full_path return None def get_node() -> str: result = find_executable('node') if result is None: raise AppiumServiceError( 'NodeJS main executable cannot be found. Make sure it is installed and present in PATH' ) return result def get_npm() -> str: result = find_executable('npm.cmd' if sys.platform == 'win32' else 'npm') if result is None: raise AppiumServiceError( 'Node Package Manager executable cannot be found. Make sure it is installed and present in PATH' ) return result def get_main_script(node: Optional[str], npm: Optional[str]) -> str: result: Optional[str] = None npm_path = npm or get_npm() for args in [['root', '-g'], ['root']]: try: modules_root = sp.check_output([npm_path] + args).strip().decode('utf-8') if os.path.exists(os.path.join(modules_root, MAIN_SCRIPT_PATH)): result = os.path.join(modules_root, MAIN_SCRIPT_PATH) break except sp.CalledProcessError: continue if result is None: node_path = node or get_node() try: result = ( sp.check_output([node_path, '-e', f'console.log(require.resolve("{MAIN_SCRIPT_PATH}"))']) .decode('utf-8') .strip() ) except sp.CalledProcessError as e: raise AppiumServiceError(e.output) from e return result def parse_arg_value(args: List[str], arg_names: Set[str], default: str) -> str: for idx, arg in enumerate(args): if arg in arg_names and idx < len(args) - 1: return args[idx + 1] return default def parse_port(args: List[str]) -> int: return int(parse_arg_value(args, {'--port', '-p'}, str(DEFAULT_PORT))) def parse_base_path(args: List[str]) -> str: return parse_arg_value(args, {'--base-path', '-pa'}, DEFAULT_BASE_PATH) def parse_host(args: List[str]) -> str: return parse_arg_value(args, {'--address', '-a'}, DEFAULT_HOST) def make_status_url(args: List[str]) -> str: base_path = parse_base_path(args) return STATUS_URL if base_path == DEFAULT_BASE_PATH else f'{re.sub(r"/+$", "", base_path)}{STATUS_URL}' class AppiumService: def __init__(self) -> None: self._process: Optional[sp.Popen] = None self._cmd: Optional[List[str]] = None def _poll_status(self, host: str, port: int, path: str, timeout_ms: int) -> bool: time_started_sec = time.time() conn = urllib3.PoolManager(timeout=1.0) while time.time() < time_started_sec + timeout_ms / 1000.0: if not self.is_running: raise AppiumStartupError() # noinspection PyUnresolvedReferences try: resp = conn.request('HEAD', f'http://{host}:{port}{path}') if resp.status < 400: return True except urllib3.exceptions.HTTPError: pass time.sleep(1.0) return False def start(self, **kwargs: Any) -> sp.Popen: """Starts Appium service with given arguments. If you use the service to start Appium 1.x then consider providing ['--base-path', '/wd/hub'] arguments. By default, the service assumes Appium server listens on '/' path, which is the default path for Appium 2. The service will be forcefully restarted if it is already running. Keyword Args: env (dict): Environment variables mapping. The default system environment, which is inherited from the parent process, is assigned by default. node (str): The full path to the main NodeJS executable. The service will try to retrieve it automatically if not provided. npm (str): The full path to the Node Package Manager (npm) script. The service will try to retrieve it automatically if not provided. stdout (int): Check the documentation for subprocess.Popen for more details. The default value is subprocess.DEVNULL on Windows and subprocess.PIPE on other platforms. stderr (int): Check the documentation for subprocess.Popen for more details. The default value is subprocess.DEVNULL on Windows and subprocess.PIPE on other platforms. timeout_ms (int): The maximum time to wait until Appium process starts listening for HTTP connections. If set to zero or a negative number then no wait will be applied. 60000 ms by default. main_script (str): The full path to the main Appium executable (usually located at build/lib/main.js). If not set then the service tries to detect the path automatically. args (str): List of Appium arguments (all must be strings). Check https://appium.io/docs/en/writing-running-appium/server-args/ for more details about possible arguments and their values. Returns: You can use Popen.communicate interface or stderr/stdout properties of the instance (stdout/stderr must not be set to None in such case) in order to retrieve the actual process output. """ self.stop() env = kwargs['env'] if 'env' in kwargs else None node: str = kwargs.get('node') or get_node() npm: str = kwargs.get('npm') or get_npm() main_script: str = kwargs.get('main_script') or get_main_script(node, npm) # A workaround for https://github.com/appium/python-client/issues/534 default_std = sp.DEVNULL if sys.platform == 'win32' else sp.PIPE stdout = kwargs['stdout'] if 'stdout' in kwargs else default_std stderr = kwargs['stderr'] if 'stderr' in kwargs else default_std timeout_ms = int(kwargs['timeout_ms']) if 'timeout_ms' in kwargs else STARTUP_TIMEOUT_MS args: List[str] = [node, main_script] if 'args' in kwargs: args.extend(kwargs['args']) self._cmd = args self._process = sp.Popen(args=args, stdout=stdout, stderr=stderr, env=env) error_msg: Optional[str] = None startup_failure_msg = ( 'Appium server process is unable to start. Make sure proper values have been ' f'provided to \'node\' ({node}), \'npm\' ({npm}) and \'main_script\' ({main_script}) ' f'method arguments.' ) if timeout_ms > 0: status_url_path = make_status_url(args) try: if not self._poll_status(parse_host(args), parse_port(args), status_url_path, timeout_ms): error_msg = ( f'Appium server has started but is not listening on {status_url_path} ' f'within {timeout_ms}ms timeout. Make sure proper values have been provided ' f'to --base-path, --address and --port process arguments.' ) except AppiumStartupError: error_msg = startup_failure_msg elif not self.is_running: error_msg = startup_failure_msg if error_msg is not None: if stderr == sp.PIPE and self._process.stderr is not None: err_output = self._process.stderr.read() if err_output: error_msg += f'\nOriginal error: {str(err_output)}' self.stop() raise AppiumServiceError(error_msg) return self._process def stop(self) -> bool: """Stops Appium service if it is running. The call will be ignored if the service is not running or has been already stopped. Returns: `True` if the service was running before being stopped """ is_terminated = False if self.is_running: assert self._process self._process.terminate() is_terminated = True self._process = None self._cmd = None return is_terminated @property def is_running(self) -> bool: """Check if the service is running. Returns: bool: `True` if the service is running """ return self._process is not None and self._cmd is not None and self._process.poll() is None @property def is_listening(self) -> bool: """Check if the service is listening on the given/default host/port. The fact, that the service is running, does not always mean it is listening. The default host/port/base path values can be customized by providing --address/--port/--base-path command line arguments while starting the service. Returns: bool: `True` if the service is running and listening on the given/default host/port """ if not self.is_running: return False assert self._cmd try: return self._poll_status(parse_host(self._cmd), parse_port(self._cmd), make_status_url(self._cmd), 1000) except AppiumStartupError: return False if __name__ == '__main__': assert find_executable('node') is not None assert find_executable('npm') is not None service = AppiumService() service.start(args=['--address', '127.0.0.1', '-p', str(DEFAULT_PORT)]) # service.start(args=['--address', '127.0.0.1', '-p', '80'], timeout_ms=2000) assert service.is_running assert service.is_listening service.stop() assert not service.is_running assert not service.is_listening
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/appium_service.py
appium_service.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # pylint: disable=too-many-lines,too-many-public-methods,too-many-statements,no-self-use import warnings from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union from selenium import webdriver from selenium.common.exceptions import ( InvalidArgumentException, SessionNotCreatedException, UnknownMethodException, WebDriverException, ) from selenium.webdriver.common.by import By from selenium.webdriver.remote.command import Command as RemoteCommand from selenium.webdriver.remote.remote_connection import RemoteConnection from appium.common.logger import logger from appium.options.common.base import AppiumOptions from appium.webdriver.common.appiumby import AppiumBy from .appium_connection import AppiumConnection from .errorhandler import MobileErrorHandler from .extensions.action_helpers import ActionHelpers from .extensions.android.activities import Activities from .extensions.android.common import Common from .extensions.android.display import Display from .extensions.android.gsm import Gsm from .extensions.android.network import Network from .extensions.android.performance import Performance from .extensions.android.power import Power from .extensions.android.sms import Sms from .extensions.android.system_bars import SystemBars from .extensions.applications import Applications from .extensions.clipboard import Clipboard from .extensions.context import Context from .extensions.device_time import DeviceTime from .extensions.execute_driver import ExecuteDriver from .extensions.execute_mobile_command import ExecuteMobileCommand from .extensions.hw_actions import HardwareActions from .extensions.images_comparison import ImagesComparison from .extensions.ime import IME from .extensions.keyboard import Keyboard from .extensions.location import Location from .extensions.log_event import LogEvent from .extensions.remote_fs import RemoteFS from .extensions.screen_record import ScreenRecord from .extensions.session import Session from .extensions.settings import Settings from .mobilecommand import MobileCommand as Command from .switch_to import MobileSwitchTo from .webelement import WebElement as MobileWebElement class ExtensionBase: """ Used to define an extension command as driver's methods. Example: When you want to add `example_command` which calls a get request to `session/$sessionId/path/to/your/custom/url`. 1. Defines an extension as a subclass of `ExtensionBase` class YourCustomCommand(ExtensionBase): def method_name(self): return 'custom_method_name' # Define a method with the name of `method_name` def custom_method_name(self): # Generally the response of Appium follows `{ 'value': { data } }` # format. return self.execute()['value'] # Used to register the command pair as "Appium command" in this driver. def add_command(self): return ('GET', 'session/$sessionId/path/to/your/custom/url') 2. Creates a session with the extension. # Appium capabilities options = AppiumOptions() driver = webdriver.Remote('http://localhost:4723/wd/hub', options=options, extensions=[YourCustomCommand]) 3. Calls the custom command # Then, the driver calls a get request against # `session/$sessionId/path/to/your/custom/url`. `$sessionId` will be # replaced properly in the driver. Then, the method returns # the `value` part of the response. driver.custom_method_name() 4. Remove added commands (if needed) # New commands are added by `setattr`. They remain in the module, # so you should explicitly delete them to define the same name method # with different arguments or process in the method. driver.delete_extensions() You can give arbitrary arguments for the command like the below. class YourCustomCommand(ExtensionBase): def method_name(self): return 'custom_method_name' def test_command(self, argument): return self.execute(argument)['value'] def add_command(self): return ('post', 'session/$sessionId/path/to/your/custom/url') driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps, extensions=[YourCustomCommand]) # Then, the driver sends a post request to `session/$sessionId/path/to/your/custom/url` # with `{'dummy_arg': 'as a value'}` JSON body. driver.custom_method_name({'dummy_arg': 'as a value'}) When you customize the URL dinamically with element id. class CustomURLCommand(ExtensionBase): def method_name(self): return 'custom_method_name' def custom_method_name(self, element_id): return self.execute({'id': element_id})['value'] def add_command(self): return ('GET', 'session/$sessionId/path/to/your/custom/$id/url') driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps, extensions=[YourCustomCommand]) element = driver.find_elemeent(by=AppiumBy.ACCESSIBILITY_ID, value='id') # Then, the driver calls a get request to `session/$sessionId/path/to/your/custom/$id/url` # with replacing the `$id` with the given `element.id` driver.custom_method_name(element.id) """ def __init__(self, execute: Callable[[str, Dict], Dict[str, Any]]): self._execute = execute def execute(self, parameters: Union[Dict[str, Any], None] = None) -> Any: param = {} if parameters: param = parameters return self._execute(self.method_name(), param) def method_name(self) -> str: """ Expected to return a method name. This name will be available as a driver method. Returns: 'str' The method name. """ raise NotImplementedError() def add_command(self) -> Tuple[str, str]: """ Expected to define the pair of HTTP method and its URL. """ raise NotImplementedError() class WebDriver( webdriver.Remote, ActionHelpers, Activities, Applications, Clipboard, Context, Common, DeviceTime, Display, ExecuteDriver, ExecuteMobileCommand, Gsm, HardwareActions, ImagesComparison, IME, Keyboard, Location, LogEvent, Network, Performance, Power, RemoteFS, ScreenRecord, Session, Settings, Sms, SystemBars, ): def __init__( self, command_executor: Union[str, AppiumConnection] = 'http://127.0.0.1:4444/wd/hub', # TODO: Remove the deprecated arg desired_capabilities: Optional[Dict] = None, # TODO: Remove the deprecated arg browser_profile: Union[str, None] = None, # TODO: Remove the deprecated arg proxy: Union[str, None] = None, keep_alive: bool = True, direct_connection: bool = True, extensions: Optional[List['WebDriver']] = None, strict_ssl: bool = True, options: Union[AppiumOptions, List[AppiumOptions], None] = None, ): if strict_ssl is False: # pylint: disable=E1101 # noinspection PyPackageRequirements import urllib3 # pylint: disable=E1101 # noinspection PyPackageRequirements import urllib3.exceptions # noinspection PyUnresolvedReferences AppiumConnection.set_certificate_bundle_path(None) urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) if isinstance(command_executor, str): command_executor = AppiumConnection(command_executor, keep_alive=keep_alive) if browser_profile is not None: warnings.warn('browser_profile argument is deprecated and has no effect', DeprecationWarning) if proxy is not None: warnings.warn('proxy argument is deprecated and has no effect', DeprecationWarning) if desired_capabilities is not None: warnings.warn( 'desired_capabilities argument is deprecated and will be removed in future versions. ' 'Use options instead.', DeprecationWarning, ) # TODO: Remove the fallback after desired_capabilities removal dst_options = ( AppiumOptions().load_capabilities(desired_capabilities) if desired_capabilities is not None and options is None else options ) super().__init__( command_executor=command_executor, options=dst_options, ) if hasattr(self, 'command_executor'): self._add_commands() self.error_handler = MobileErrorHandler() if direct_connection: self._update_command_executor(keep_alive=keep_alive) # add new method to the `find_by_*` pantheon By.IOS_UIAUTOMATION = AppiumBy.IOS_UIAUTOMATION By.IOS_PREDICATE = AppiumBy.IOS_PREDICATE By.IOS_CLASS_CHAIN = AppiumBy.IOS_CLASS_CHAIN By.ANDROID_UIAUTOMATOR = AppiumBy.ANDROID_UIAUTOMATOR By.ANDROID_VIEWTAG = AppiumBy.ANDROID_VIEWTAG By.WINDOWS_UI_AUTOMATION = AppiumBy.WINDOWS_UI_AUTOMATION By.ACCESSIBILITY_ID = AppiumBy.ACCESSIBILITY_ID By.IMAGE = AppiumBy.IMAGE By.CUSTOM = AppiumBy.CUSTOM self._absent_extensions: Set[str] = set() self._extensions = extensions or [] for extension in self._extensions: instance = extension(self.execute) method_name = instance.method_name() if hasattr(WebDriver, method_name): logger.debug(f"Overriding the method '{method_name}'") # add a new method named 'instance.method_name()' and call it setattr(WebDriver, method_name, getattr(instance, method_name)) method, url_cmd = instance.add_command() # noinspection PyProtectedMember self.command_executor._commands[method_name] = (method.upper(), url_cmd) # type: ignore def delete_extensions(self) -> None: """Delete extensions added in the class with 'setattr'""" for extension in self._extensions: instance = extension(self.execute) method_name = instance.method_name() if hasattr(WebDriver, method_name): delattr(WebDriver, method_name) def _update_command_executor(self, keep_alive: bool) -> None: """Update command executor following directConnect feature""" direct_protocol = 'directConnectProtocol' direct_host = 'directConnectHost' direct_port = 'directConnectPort' direct_path = 'directConnectPath' assert self.caps, 'Driver capabilities must be defined' if not {direct_protocol, direct_host, direct_port, direct_path}.issubset(set(self.caps)): message = 'Direct connect capabilities from server were:\n' for key in [direct_protocol, direct_host, direct_port, direct_path]: message += f'{key}: \'{self.caps.get(key, "")}\' ' logger.debug(message) return protocol = self.caps[direct_protocol] hostname = self.caps[direct_host] port = self.caps[direct_port] path = self.caps[direct_path] executor = f'{protocol}://{hostname}:{port}{path}' logger.debug('Updated request endpoint to %s', executor) # Override command executor self.command_executor = RemoteConnection(executor, keep_alive=keep_alive) self._add_commands() # https://github.com/SeleniumHQ/selenium/blob/06fdf2966df6bca47c0ae45e8201cd30db9b9a49/py/selenium/webdriver/remote/webdriver.py#L277 # noinspection PyAttributeOutsideInit def start_session(self, capabilities: Union[Dict, AppiumOptions], browser_profile: Optional[str] = None) -> None: """Creates a new session with the desired capabilities. Override for Appium Args: capabilities: Read https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md for more details. browser_profile: Browser profile """ if not isinstance(capabilities, (dict, AppiumOptions)): raise InvalidArgumentException('Capabilities must be a dictionary or AppiumOptions instance') w3c_caps = AppiumOptions.as_w3c(capabilities) if isinstance(capabilities, dict) else capabilities.to_w3c() response = self.execute(RemoteCommand.NEW_SESSION, w3c_caps) # https://w3c.github.io/webdriver/#new-session if not isinstance(response, dict): raise SessionNotCreatedException( f'A valid W3C session creation response must be a dictionary. Got "{response}" instead' ) # Due to a W3C spec parsing misconception some servers # pack the createSession response stuff into 'value' dictionary and # some other put it to the top level of the response JSON nesting hierarchy get_response_value: Callable[[str], Optional[Any]] = lambda key: response.get(key) or ( response['value'].get(key) if isinstance(response.get('value'), dict) else None ) session_id = get_response_value('sessionId') if not session_id: raise SessionNotCreatedException( f'A valid W3C session creation response must contain a non-empty "sessionId" entry. ' f'Got "{response}" instead' ) self.session_id = session_id self.caps = get_response_value('capabilities') or {} def get_status(self) -> Dict: """ Get the Appium server status Usage: driver.get_status() Returns: Dict: The status information """ return self.execute(Command.GET_STATUS)['value'] def find_element(self, by: str = AppiumBy.ID, value: Union[str, Dict, None] = None) -> MobileWebElement: """ Find an element given a AppiumBy strategy and locator Args: by: The strategy value: The locator Usage: driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value='accessibility_id') Returns: `appium.webdriver.webelement.WebElement`: The found element """ # We prefer to patch locators in the client code # Checking current context every time a locator is accessed could significantly slow down tests # Check https://github.com/appium/python-client/pull/724 before submitting any issue # if by == By.ID: # by = By.CSS_SELECTOR # value = '[id="%s"]' % value # elif by == By.TAG_NAME: # by = By.CSS_SELECTOR # elif by == By.CLASS_NAME: # by = By.CSS_SELECTOR # value = ".%s" % value # elif by == By.NAME: # by = By.CSS_SELECTOR # value = '[name="%s"]' % value return self.execute(RemoteCommand.FIND_ELEMENT, {'using': by, 'value': value})['value'] def find_elements( self, by: str = AppiumBy.ID, value: Union[str, Dict, None] = None ) -> Union[List[MobileWebElement], List]: """ Find elements given a AppiumBy strategy and locator Args: by: The strategy value: The locator Usage: driver.find_elements(by=AppiumBy.ACCESSIBILITY_ID, value='accessibility_id') Returns: :obj:`list` of :obj:`appium.webdriver.webelement.WebElement`: The found elements """ # We prefer to patch locators in the client code # Checking current context every time a locator is accessed could significantly slow down tests # Check https://github.com/appium/python-client/pull/724 before submitting any issue # if by == By.ID: # by = By.CSS_SELECTOR # value = '[id="%s"]' % value # elif by == By.TAG_NAME: # by = By.CSS_SELECTOR # elif by == By.CLASS_NAME: # by = By.CSS_SELECTOR # value = ".%s" % value # elif by == By.NAME: # by = By.CSS_SELECTOR # value = '[name="%s"]' % value # Return empty list if driver returns null # See https://github.com/SeleniumHQ/selenium/issues/4555 return self.execute(RemoteCommand.FIND_ELEMENTS, {'using': by, 'value': value})['value'] or [] def create_web_element(self, element_id: Union[int, str]) -> MobileWebElement: """Creates a web element with the specified element_id. Overrides method in Selenium WebDriver in order to always give them Appium WebElement Args: element_id: The element id to create a web element Returns: `MobileWebElement` """ return MobileWebElement(self, element_id) def set_value(self, element: MobileWebElement, value: str) -> 'WebDriver': """Set the value on an element in the application. deprecated:: 2.8.1 Args: element: the element whose value will be set value: the value to set on the element Returns: `appium.webdriver.webdriver.WebDriver`: Self instance """ warnings.warn( 'The "setValue" API is deprecated and will be removed in future versions. ' 'Instead the "send_keys" API or W3C Actions can be used. ' 'See https://github.com/appium/python-client/pull/831', DeprecationWarning, ) data = {'text': value} self.execute(Command.SET_IMMEDIATE_VALUE, data) return self @property def switch_to(self) -> MobileSwitchTo: """Returns an object containing all options to switch focus into Override for appium Returns: `appium.webdriver.switch_to.MobileSwitchTo` """ return MobileSwitchTo(self) # MJSONWP for Selenium v4 @property def orientation(self) -> str: """ Gets the current orientation of the device :Usage: :: orientation = driver.orientation """ return self.execute(Command.GET_SCREEN_ORIENTATION)['value'] # MJSONWP for Selenium v4 @orientation.setter def orientation(self, value: str) -> None: """ Sets the current orientation of the device :Args: - value: orientation to set it to. :Usage: :: driver.orientation = 'landscape' """ allowed_values = ['LANDSCAPE', 'PORTRAIT'] if value.upper() in allowed_values: self.execute(Command.SET_SCREEN_ORIENTATION, {'orientation': value}) else: raise WebDriverException("You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'") def assert_extension_exists(self, ext_name: str) -> 'WebDriver': """ Verifies if the given extension is not present in the list of absent extensions for the given driver instance. This API is designed for private usage. :param ext_name: extension name :return: self instance for chaining :raise UnknownMethodException: If the extension has been marked as absent once """ if ext_name in self._absent_extensions: raise UnknownMethodException() return self def mark_extension_absence(self, ext_name: str) -> 'WebDriver': """ Marks the given extension as absent for the given driver instance. This API is designed for private usage. :param ext_name: extension name :return: self instance for chaining """ logger.debug(f'Marking driver extension "{ext_name}" as absent for the current instance') self._absent_extensions.add(ext_name) return self def _add_commands(self) -> None: # call the overridden command binders from all mixin classes except for # appium.webdriver.webdriver.WebDriver and its sub-classes # https://github.com/appium/python-client/issues/342 for mixin_class in filter(lambda x: not issubclass(x, WebDriver), self.__class__.__mro__): if hasattr(mixin_class, self._add_commands.__name__): get_atter = getattr(mixin_class, self._add_commands.__name__, None) if get_atter: get_atter(self) # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.GET_STATUS] = ('GET', '/status') # FIXME: remove after a while as MJSONWP commands[Command.TOUCH_ACTION] = ('POST', '/session/$sessionId/touch/perform') commands[Command.MULTI_ACTION] = ('POST', '/session/$sessionId/touch/multi/perform') commands[Command.SET_IMMEDIATE_VALUE] = ( 'POST', '/session/$sessionId/appium/element/$id/value', ) # TODO Move commands for element to webelement commands[Command.REPLACE_KEYS] = ( 'POST', '/session/$sessionId/appium/element/$id/replace_value', ) commands[Command.CLEAR] = ('POST', '/session/$sessionId/element/$id/clear') commands[Command.LOCATION_IN_VIEW] = ( 'GET', '/session/$sessionId/element/$id/location_in_view', ) # MJSONWP for Selenium v4 commands[Command.IS_ELEMENT_DISPLAYED] = ('GET', '/session/$sessionId/element/$id/displayed') commands[Command.GET_CAPABILITIES] = ('GET', '/session/$sessionId') commands[Command.GET_SCREEN_ORIENTATION] = ('GET', '/session/$sessionId/orientation') commands[Command.SET_SCREEN_ORIENTATION] = ('POST', '/session/$sessionId/orientation') # override for Appium 1.x # Appium 2.0 and Appium 1.22 work with `/se/log` and `/se/log/types` # FIXME: remove after a while commands[Command.GET_LOG] = ('POST', '/session/$sessionId/log') commands[Command.GET_AVAILABLE_LOG_TYPES] = ('GET', '/session/$sessionId/log/types')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/webdriver.py
webdriver.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import Callable, Dict, List, Optional, Union from selenium.webdriver.common.utils import keys_to_typing from selenium.webdriver.remote.command import Command as RemoteCommand from selenium.webdriver.remote.webelement import WebElement as SeleniumWebElement from appium.webdriver.common.appiumby import AppiumBy from .mobilecommand import MobileCommand as Command class WebElement(SeleniumWebElement): _execute: Callable _id: str def get_attribute(self, name: str) -> Optional[Union[str, Dict]]: """Gets the given attribute or property of the element. Override for Appium This method will first try to return the value of a property with the given name. If a property with that name doesn't exist, it returns the value of the attribute with the same name. If there's no attribute with that name, ``None`` is returned. Values which are considered truthy, that is equals "true" or "false", are returned as booleans. All other non-``None`` values are returned as strings. For attributes or properties which do not exist, ``None`` is returned. Args: name: Name of the attribute/property to retrieve. Usage: # Check if the "active" CSS class is applied to an element. is_active = "active" in target_element.get_attribute("class") Returns: The given attribute or property of the element """ resp = self._execute(RemoteCommand.GET_ELEMENT_ATTRIBUTE, {'name': name}) attribute_value = resp.get('value') if attribute_value is None: return None if isinstance(attribute_value, dict): return attribute_value # Convert to str along to the spec if not isinstance(attribute_value, str): attribute_value = str(attribute_value) if name != 'value' and attribute_value.lower() in ('true', 'false'): return attribute_value.lower() return attribute_value def is_displayed(self) -> bool: """Whether the element is visible to a user. Override for Appium """ return self._execute(Command.IS_ELEMENT_DISPLAYED)['value'] def find_element(self, by: str = AppiumBy.ID, value: Union[str, Dict, None] = None) -> 'WebElement': """Find an element given a AppiumBy strategy and locator Override for Appium Prefer the find_element_by_* methods when possible. Args: by: The strategy value: The locator Usage: element = element.find_element(AppiumBy.ID, 'foo') Returns: `appium.webdriver.webelement.WebElement` """ # We prefer to patch locators in the client code # Checking current context every time a locator is accessed could significantly slow down tests # Check https://github.com/appium/python-client/pull/724 before submitting any issue # if by == By.ID: # by = By.CSS_SELECTOR # value = '[id="%s"]' % value # elif by == By.TAG_NAME: # by = By.CSS_SELECTOR # elif by == By.CLASS_NAME: # by = By.CSS_SELECTOR # value = ".%s" % value # elif by == By.NAME: # by = By.CSS_SELECTOR # value = '[name="%s"]' % value return self._execute(RemoteCommand.FIND_CHILD_ELEMENT, {"using": by, "value": value})['value'] def find_elements(self, by: str = AppiumBy.ID, value: Union[str, Dict, None] = None) -> List['WebElement']: """Find elements given a AppiumBy strategy and locator Args: by: The strategy value: The locator Usage: element = element.find_elements(AppiumBy.CLASS_NAME, 'foo') Returns: :obj:`list` of :obj:`appium.webdriver.webelement.WebElement` """ # We prefer to patch locators in the client code # Checking current context every time a locator is accessed could significantly slow down tests # Check https://github.com/appium/python-client/pull/724 before submitting any issue # if by == By.ID: # by = By.CSS_SELECTOR # value = '[id="%s"]' % value # elif by == By.TAG_NAME: # by = By.CSS_SELECTOR # elif by == By.CLASS_NAME: # by = By.CSS_SELECTOR # value = ".%s" % value # elif by == By.NAME: # by = By.CSS_SELECTOR # value = '[name="%s"]' % value return self._execute(RemoteCommand.FIND_CHILD_ELEMENTS, {"using": by, "value": value})['value'] def clear(self) -> 'WebElement': """Clears text. Override for Appium Returns: `appium.webdriver.webelement.WebElement` """ # NOTE: this method is overridden because the selenium client returned None instead of self. # Appium python cleint would like to allow users to chain methods. data = {'id': self.id} self._execute(Command.CLEAR, data) return self def set_text(self, keys: str = '') -> 'WebElement': """Sends text to the element. deprecated:: 2.8.1 Previous text is removed. Android only. Args: keys: the text to be sent to the element. Usage: element.set_text('some text') Returns: `appium.webdriver.webelement.WebElement` """ warnings.warn( 'The "setText" API is deprecated and will be removed in future versions. ' 'Instead the "send_keys" API or W3C Actions can be used. ' 'See https://github.com/appium/python-client/pull/831', DeprecationWarning, ) data = {'text': keys} self._execute(Command.REPLACE_KEYS, data) return self @property def location_in_view(self) -> Dict[str, int]: """Gets the location of an element relative to the view. Usage: | location = element.location_in_view | x = location['x'] | y = location['y'] Returns: dict: The location of an element relative to the view """ return self._execute(Command.LOCATION_IN_VIEW)['value'] def set_value(self, value: str) -> 'WebElement': """Set the value on this element in the application deprecated:: 2.8.1 Args: value: The value to be set Returns: `appium.webdriver.webelement.WebElement` """ warnings.warn( 'The "setValue" API is deprecated and will be removed in future versions. ' 'Instead the "send_keys" API or W3C Actions can be used. ' 'See https://github.com/appium/python-client/pull/831', DeprecationWarning, ) data = {'text': value} self._execute(Command.SET_IMMEDIATE_VALUE, data) return self # Override def send_keys(self, *value: str) -> 'WebElement': """Simulates typing into the element. Args: value: A string for typing. Returns: `appium.webdriver.webelement.WebElement` """ keys = keys_to_typing(value) self._execute(RemoteCommand.SEND_KEYS_TO_ELEMENT, {'text': ''.join(keys), 'value': keys}) return self
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/webelement.py
webelement.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class MobileCommand: # Common GET_SESSION = 'getSession' GET_ALL_SESSIONS = 'getAllSessions' GET_STATUS = 'getStatus' ## MJSONWP for Selenium v4 GET_LOCATION = 'getLocation' SET_LOCATION = 'setLocation' ## MJSONWP for Selenium v4 GET_AVAILABLE_IME_ENGINES = 'getAvailableIMEEngines' IS_IME_ACTIVE = 'isIMEActive' ACTIVATE_IME_ENGINE = 'activateIMEEngine' DEACTIVATE_IME_ENGINE = 'deactivateIMEEngine' GET_ACTIVE_IME_ENGINE = 'getActiveEngine' CLEAR = 'clear' LOCATION_IN_VIEW = 'locationInView' CONTEXTS = 'getContexts' GET_CURRENT_CONTEXT = 'getCurrentContext' SWITCH_TO_CONTEXT = 'switchToContext' TOUCH_ACTION = 'touchAction' MULTI_ACTION = 'multiAction' SET_IMMEDIATE_VALUE = 'setImmediateValue' REPLACE_KEYS = 'replaceKeys' LAUNCH_APP = 'launchApp' CLOSE_APP = 'closeApp' RESET = 'reset' BACKGROUND = 'background' GET_APP_STRINGS = 'getAppStrings' IS_LOCKED = 'isLocked' LOCK = 'lock' UNLOCK = 'unlock' GET_DEVICE_TIME_GET = 'getDeviceTimeGet' GET_DEVICE_TIME_POST = 'getDeviceTimePost' INSTALL_APP = 'installApp' REMOVE_APP = 'removeApp' IS_APP_INSTALLED = 'isAppInstalled' TERMINATE_APP = 'terminateApp' ACTIVATE_APP = 'activateApp' QUERY_APP_STATE = 'queryAppState' SHAKE = 'shake' HIDE_KEYBOARD = 'hideKeyboard' PRESS_KEYCODE = 'pressKeyCode' LONG_PRESS_KEYCODE = 'longPressKeyCode' KEY_EVENT = 'keyEvent' # Needed for Selendroid PUSH_FILE = 'pushFile' PULL_FILE = 'pullFile' PULL_FOLDER = 'pullFolder' GET_CLIPBOARD = 'getClipboard' SET_CLIPBOARD = 'setClipboard' FINGER_PRINT = 'fingerPrint' GET_SETTINGS = 'getSettings' UPDATE_SETTINGS = 'updateSettings' START_RECORDING_SCREEN = 'startRecordingScreen' STOP_RECORDING_SCREEN = 'stopRecordingScreen' COMPARE_IMAGES = 'compareImages' IS_KEYBOARD_SHOWN = 'isKeyboardShown' EXECUTE_DRIVER = 'executeDriver' GET_EVENTS = 'getLogEvents' LOG_EVENT = 'logCustomEvent' ## MJSONWP for Selenium v4 IS_ELEMENT_DISPLAYED = 'isElementDisplayed' GET_CAPABILITIES = 'getCapabilities' GET_SCREEN_ORIENTATION = 'getScreenOrientation' SET_SCREEN_ORIENTATION = 'setScreenOrientation' # To override selenium commands GET_LOG = 'getLog' GET_AVAILABLE_LOG_TYPES = 'getAvailableLogTypes' # Android OPEN_NOTIFICATIONS = 'openNotifications' START_ACTIVITY = 'startActivity' GET_CURRENT_ACTIVITY = 'getCurrentActivity' GET_CURRENT_PACKAGE = 'getCurrentPackage' GET_SYSTEM_BARS = 'getSystemBars' GET_DISPLAY_DENSITY = 'getDisplayDensity' TOGGLE_WIFI = 'toggleWiFi' TOGGLE_LOCATION_SERVICES = 'toggleLocationServices' END_TEST_COVERAGE = 'endTestCoverage' GET_PERFORMANCE_DATA_TYPES = 'getPerformanceDataTypes' GET_PERFORMANCE_DATA = 'getPerformanceData' GET_NETWORK_CONNECTION = 'getNetworkConnection' SET_NETWORK_CONNECTION = 'setNetworkConnection' # Android Emulator SEND_SMS = 'sendSms' MAKE_GSM_CALL = 'makeGsmCall' SET_GSM_SIGNAL = 'setGsmSignal' SET_GSM_VOICE = 'setGsmVoice' SET_NETWORK_SPEED = 'setNetworkSpeed' SET_POWER_CAPACITY = 'setPowerCapacity' SET_POWER_AC = 'setPowerAc' # iOS TOUCH_ID = 'touchId' TOGGLE_TOUCH_ID_ENROLLMENT = 'toggleTouchIdEnrollment'
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/mobilecommand.py
mobilecommand.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import uuid from typing import TYPE_CHECKING, Any, Dict, Optional, Union import urllib3 from selenium.webdriver.remote.remote_connection import RemoteConnection from appium.common.helper import library_version if TYPE_CHECKING: from urllib.parse import ParseResult PREFIX_HEADER = 'appium/' class AppiumConnection(RemoteConnection): _proxy_url: Optional[str] def __init__( self, remote_server_addr: str, keep_alive: bool = False, ignore_proxy: Optional[bool] = False, init_args_for_pool_manager: Union[Dict[str, Any], None] = None, ): # Need to call before super().__init__ in order to pass arguments for the pool manager in the super. self._init_args_for_pool_manager = init_args_for_pool_manager or {} super().__init__(remote_server_addr, keep_alive=keep_alive, ignore_proxy=ignore_proxy) def _get_connection_manager(self) -> Union[urllib3.PoolManager, urllib3.ProxyManager]: # https://github.com/SeleniumHQ/selenium/blob/0e0194b0e52a34e7df4b841f1ed74506beea5c3e/py/selenium/webdriver/remote/remote_connection.py#L134 pool_manager_init_args = {'timeout': self.get_timeout()} if self._ca_certs: pool_manager_init_args['cert_reqs'] = 'CERT_REQUIRED' pool_manager_init_args['ca_certs'] = self._ca_certs else: # This line is necessary to disable certificate verification pool_manager_init_args['cert_reqs'] = 'CERT_NONE' pool_manager_init_args.update(self._init_args_for_pool_manager) if self._proxy_url: if self._proxy_url.lower().startswith('sock'): from urllib3.contrib.socks import SOCKSProxyManager return SOCKSProxyManager(self._proxy_url, **pool_manager_init_args) if self._identify_http_proxy_auth(): self._proxy_url, self._basic_proxy_auth = self._separate_http_proxy_auth() pool_manager_init_args['proxy_headers'] = urllib3.make_headers(proxy_basic_auth=self._basic_proxy_auth) return urllib3.ProxyManager(self._proxy_url, **pool_manager_init_args) return urllib3.PoolManager(**pool_manager_init_args) @classmethod def get_remote_connection_headers(cls, parsed_url: 'ParseResult', keep_alive: bool = True) -> Dict[str, Any]: """Override get_remote_connection_headers in RemoteConnection""" headers = RemoteConnection.get_remote_connection_headers(parsed_url, keep_alive=keep_alive) # e.g. appium/0.49 (selenium/3.141.0 (python linux)) headers['User-Agent'] = f'{PREFIX_HEADER}{library_version()} ({headers["User-Agent"]})' if parsed_url.path.endswith('/session'): # https://github.com/appium/appium-base-driver/pull/400 headers['X-Idempotency-Key'] = str(uuid.uuid4()) return headers
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/appium_connection.py
appium_connection.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json from typing import Any, Dict, List, Sequence, Type, Union import selenium.common.exceptions as sel_exceptions from selenium.webdriver.remote import errorhandler import appium.common.exceptions as appium_exceptions ERROR_TO_EXC_MAPPING: Dict[str, Type[sel_exceptions.WebDriverException]] = { 'element click intercepted': sel_exceptions.ElementClickInterceptedException, 'element not interactable': sel_exceptions.ElementNotInteractableException, 'insecure certificate': sel_exceptions.InsecureCertificateException, 'invalid argument': sel_exceptions.InvalidArgumentException, 'invalid cookie domain': sel_exceptions.InvalidCookieDomainException, 'invalid element state': sel_exceptions.InvalidElementStateException, 'invalid selector': sel_exceptions.InvalidSelectorException, 'invalid session id': sel_exceptions.InvalidSessionIdException, 'javascript error': sel_exceptions.JavascriptException, 'move target out of bounds': sel_exceptions.MoveTargetOutOfBoundsException, 'no such alert': sel_exceptions.NoAlertPresentException, 'no such cookie': sel_exceptions.NoSuchCookieException, 'no such element': sel_exceptions.NoSuchElementException, 'no such frame': sel_exceptions.NoSuchFrameException, 'no such window': sel_exceptions.NoSuchWindowException, 'no such shadow root': sel_exceptions.NoSuchShadowRootException, 'script timeout': sel_exceptions.TimeoutException, 'session not created': sel_exceptions.SessionNotCreatedException, 'stale element reference': sel_exceptions.StaleElementReferenceException, 'detached shadow root': sel_exceptions.NoSuchShadowRootException, 'timeout': sel_exceptions.TimeoutException, 'unable to set cookie': sel_exceptions.UnableToSetCookieException, 'unable to capture screen': sel_exceptions.ScreenshotException, 'unexpected alert open': sel_exceptions.UnexpectedAlertPresentException, 'unknown command': sel_exceptions.UnknownMethodException, 'unknown error': sel_exceptions.WebDriverException, 'unknown method': sel_exceptions.UnknownMethodException, 'unsupported operation': sel_exceptions.UnknownMethodException, 'element not visible': sel_exceptions.ElementNotVisibleException, 'element not selectable': sel_exceptions.ElementNotSelectableException, 'invalid coordinates': sel_exceptions.InvalidCoordinatesException, } def format_stacktrace(original: Union[None, str, Sequence]) -> List[str]: if not original: return [] if isinstance(original, str): return original.split('\n') result: List[str] = [] try: for frame in original: if not isinstance(frame, dict): continue line = frame.get('lineNumber', '') file = frame.get('fileName', '<anonymous>') if line: file = f'{file}:{line}' meth = frame.get('methodName', '<anonymous>') if 'className' in frame: meth = f'{frame["className"]}.{meth}' result.append(f' at {meth} ({file})') except TypeError: pass return result class MobileErrorHandler(errorhandler.ErrorHandler): def check_response(self, response: Dict[str, Any]) -> None: """ https://www.w3.org/TR/webdriver/#errors """ payload = response.get('value', '') try: payload_dict = json.loads(payload) except (json.JSONDecodeError, TypeError): return if not isinstance(payload_dict, dict): return value = payload_dict.get('value') if not isinstance(value, dict): return error = value.get('error') if not error: return message = value.get('message', error) stacktrace = value.get('stacktrace', '') # In theory, we should also be checking HTTP status codes. # Java client, for example, prints a warning if the actual `error` # value does not match to the response's HTTP status code. exception_class: Type[sel_exceptions.WebDriverException] = ERROR_TO_EXC_MAPPING.get( error, sel_exceptions.WebDriverException ) if exception_class is sel_exceptions.WebDriverException and message: if message == 'No such context found.': exception_class = appium_exceptions.NoSuchContextException elif message == 'That command could not be executed in the current context.': exception_class = appium_exceptions.InvalidSwitchToTargetException if exception_class is sel_exceptions.UnexpectedAlertPresentException: raise sel_exceptions.UnexpectedAlertPresentException( msg=message, stacktrace=format_stacktrace(stacktrace), alert_text=value.get('data'), ) raise exception_class(msg=message, stacktrace=format_stacktrace(stacktrace))
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/errorhandler.py
errorhandler.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from ..mobilecommand import MobileCommand as Command class Context(CanExecuteCommands): @property def contexts(self) -> List[str]: """Returns the contexts within the current session. Usage: driver.contexts Return: :obj:`list` of :obj:`str`: The contexts within the current session """ return self.execute(Command.CONTEXTS)['value'] @property def current_context(self) -> str: """Returns the current context of the current session. Usage: driver.current_context Return: str: The context of the current session """ return self.execute(Command.GET_CURRENT_CONTEXT)['value'] @property def context(self) -> str: """Returns the current context of the current session. Usage: driver.context Return: str: The context of the current session """ return self.current_context def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.CONTEXTS] = ('GET', '/session/$sessionId/contexts') commands[Command.GET_CURRENT_CONTEXT] = ('GET', '/session/$sessionId/context') commands[Command.SWITCH_TO_CONTEXT] = ('POST', '/session/$sessionId/context')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/context.py
context.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Dict, Union from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from ..mobilecommand import MobileCommand as Command class ImagesComparison(CanExecuteCommands): def match_images_features(self, base64_image1: bytes, base64_image2: bytes, **opts: Any) -> Dict[str, Any]: """Performs images matching by features. Read https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_matcher/py_matcher.html for more details on this topic. The method supports all image formats, which are supported by OpenCV itself. Args: base64_image1: base64-encoded content of the first image base64_image2: base64-encoded content of the second image Keyword Args: visualize (bool): Set it to True in order to return the visualization of the matching operation. matching visualization. False by default detectorName (str): One of possible feature detector names: 'AKAZE', 'AGAST', 'BRISK', 'FAST', 'GFTT', 'KAZE', 'MSER', 'SIFT', 'ORB' Some of these detectors are not enabled in the default OpenCV deployment. 'ORB' By default. matchFunc (str): One of supported matching functions names: 'FlannBased', 'BruteForce', 'BruteForceL1', 'BruteForceHamming', 'BruteForceHammingLut', 'BruteForceSL2' 'BruteForce' by default goodMatchesFactor (int): The maximum count of "good" matches (e. g. with minimal distances). This count is unlimited by default. Returns: The dictionary containing the following entries: visualization (bytes): base64-encoded content of PNG visualization of the current comparison operation. This entry is only present if `visualize` option is enabled count (int): The count of matched edges on both images. The more matching edges there are no both images the more similar they are. totalCount (int): The total count of matched edges on both images. It is equal to `count` if `goodMatchesFactor` does not limit the matches, otherwise it contains the total count of matches before `goodMatchesFactor` is applied. points1 (dict): The array of matching points on the first image. Each point is a dictionary with 'x' and 'y' keys rect1 (dict): The bounding rect for the `points1` array or a zero rect if not enough matching points were found. The rect is represented by a dictionary with 'x', 'y', 'width' and 'height' keys points2 (dict): The array of matching points on the second image. Each point is a dictionary with 'x' and 'y' keys rect2 (dict): The bounding rect for the `points2` array or a zero rect if not enough matching points were found. The rect is represented by a dictionary with 'x', 'y', 'width' and 'height' keys """ options = {'mode': 'matchFeatures', 'firstImage': base64_image1, 'secondImage': base64_image2, 'options': opts} return self.execute(Command.COMPARE_IMAGES, options)['value'] def find_image_occurrence( self, base64_full_image: bytes, base64_partial_image: bytes, **opts: Any ) -> Dict[str, Union[bytes, Dict]]: """Performs images matching by template to find possible occurrence of the partial image in the full image. Read https://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html for more details on this topic. The method supports all image formats, which are supported by OpenCV itself. Args: base64_full_image: base64-encoded content of the full image base64_partial_image: base64-encoded content of the partial image Keyword Args: visualize (bool): Set it to True in order to return the visualization of the matching operation. False by default Returns: The dictionary containing the following entries: visualization (bytes): base64-encoded content of PNG visualization of the current comparison operation. This entry is only present if `visualize` option is enabled rect (dict): The region of the partial image occurrence on the full image. The rect is represented by a dictionary with 'x', 'y', 'width' and 'height' keys """ options = { 'mode': 'matchTemplate', 'firstImage': base64_full_image, 'secondImage': base64_partial_image, 'options': opts, } return self.execute(Command.COMPARE_IMAGES, options)['value'] def get_images_similarity( self, base64_image1: bytes, base64_image2: bytes, **opts: Any ) -> Dict[str, Union[bytes, Dict]]: """Performs images matching to calculate the similarity score between them. The flow there is similar to the one used in `find_image_occurrence`, but it is mandatory that both images are of equal resolution. The method supports all image formats, which are supported by OpenCV itself. Args: base64_image1: base64-encoded content of the first image base64_image2: base64-encoded content of the second image Keyword Args: visualize (boo): Set it to True in order to return the visualization of the matching operation. False by default Returns: The dictionary containing the following entries: visualization (bytes): base64-encoded content of PNG visualization of the current comparison operation. This entry is only present if `visualize` option is enabled score (float): The similarity score as a float number in range [0.0, 1.0]. 1.0 is the highest score (means both images are totally equal). """ options = {'mode': 'getSimilarity', 'firstImage': base64_image1, 'secondImage': base64_image2, 'options': opts} return self.execute(Command.COMPARE_IMAGES, options)['value'] def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.COMPARE_IMAGES] = ('POST', '/session/$sessionId/appium/compare_images')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/images_comparison.py
images_comparison.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Dict, Optional, Union from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from ..mobilecommand import MobileCommand as Command class ExecuteDriver(CanExecuteCommands): # TODO Inner class case def execute_driver(self, script: str, script_type: str = 'webdriverio', timeout_ms: Optional[int] = None) -> Any: """Run a set of script against the current session, allowing execution of many commands in one Appium request. Please read http://appium.io/docs/en/commands/session/execute-driver for more details about the acceptable scripts and the output format. Args: script: The string consisting of the script itself script_type: The name of the script type. Defaults to 'webdriverio'. timeout_ms: The number of `ms` Appium should wait for the script to finish before killing it due to timeout_ms. Usage: | self.driver.execute_driver(script='return [];') | self.driver.execute_driver(script='return [];', script_type='webdriverio') | self.driver.execute_driver(script='return [];', script_type='webdriverio', timeout_ms=10000) Returns: ExecuteDriver.Result: The result of the script. It has 'result' and 'logs' keys. Raises: WebDriverException: If something error happenes in the script. The message has the original error message. """ class Result: def __init__(self, res: Dict): self.result = res['result'] self.logs = res['logs'] option: Dict[str, Union[str, int]] = {'script': script, 'type': script_type} if timeout_ms is not None: option['timeout'] = timeout_ms response = self.execute(Command.EXECUTE_DRIVER, option)['value'] return Result(response) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.EXECUTE_DRIVER] = ('POST', '/session/$sessionId/appium/execute_driver')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/execute_driver.py
execute_driver.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 from typing import TYPE_CHECKING, Optional, cast from selenium.common.exceptions import InvalidArgumentException, UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from ..mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class RemoteFS(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): def pull_file(self, path: str) -> str: """Retrieves the file at `path`. Args: path: the path to the file on the device Returns: The file's contents encoded as Base64. """ ext_name = 'mobile: pullFile' try: return self.assert_extension_exists(ext_name).execute_script(ext_name, {'remotePath': path}) except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute(Command.PULL_FILE, {'path': path})['value'] def pull_folder(self, path: str) -> str: """Retrieves a folder at `path`. Args: path: the path to the folder on the device Returns: The folder's contents zipped and encoded as Base64. """ ext_name = 'mobile: pullFolder' try: return self.assert_extension_exists(ext_name).execute_script(ext_name, {'remotePath': path}) except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute(Command.PULL_FOLDER, {'path': path})['value'] def push_file( self, destination_path: str, base64data: Optional[str] = None, source_path: Optional[str] = None ) -> 'WebDriver': """Puts the data from the file at `source_path`, encoded as Base64, in the file specified as `path`. Specify either `base64data` or `source_path`, if both specified default to `source_path` Args: destination_path: the location on the device/simulator where the local file contents should be saved base64data: file contents, encoded as Base64, to be written to the file on the device/simulator source_path: local file path for the file to be loaded on device Returns: Union['WebDriver', 'RemoteFS']: Self instance """ if source_path is None and base64data is None: raise InvalidArgumentException('Must either pass base64 data or a local file path') if source_path is not None: try: with open(source_path, 'rb') as f: file_data = f.read() except IOError as e: message = f'source_path "{source_path}" could not be found. Are you sure the file exists?' raise InvalidArgumentException(message) from e base64data = base64.b64encode(file_data).decode('utf-8') ext_name = 'mobile: pushFile' try: self.assert_extension_exists(ext_name).execute_script( ext_name, { 'remotePath': destination_path, 'payload': base64data, }, ) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute( Command.PUSH_FILE, { 'path': destination_path, 'data': base64data, }, ) return cast('WebDriver', self) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.PULL_FILE] = ('POST', '/session/$sessionId/appium/device/pull_file') commands[Command.PULL_FOLDER] = ('POST', '/session/$sessionId/appium/device/pull_folder') commands[Command.PUSH_FILE] = ('POST', '/session/$sessionId/appium/device/push_file')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/remote_fs.py
remote_fs.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, Optional, cast from selenium.common.exceptions import UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from ..mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class HardwareActions(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): def lock(self, seconds: Optional[int] = None) -> 'WebDriver': """Lock the device. No changes are made if the device is already unlocked. Args: seconds: The duration to lock the device, in seconds. The device is going to be locked forever until `unlock` is called if it equals or is less than zero, otherwise this call blocks until the timeout expires and unlocks the screen automatically. Returns: Union['WebDriver', 'HardwareActions']: Self instance """ ext_name = 'mobile: lock' args = {'seconds': seconds or 0} try: self.assert_extension_exists(ext_name).execute_script(ext_name, args) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.LOCK, args) return cast('WebDriver', self) def unlock(self) -> 'WebDriver': """Unlock the device. No changes are made if the device is already locked. Returns: Union['WebDriver', 'HardwareActions']: Self instance """ ext_name = 'mobile: unlock' try: if not self.assert_extension_exists(ext_name).execute_script('mobile: isLocked'): return cast('WebDriver', self) self.execute_script(ext_name) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.UNLOCK) return cast('WebDriver', self) def is_locked(self) -> bool: """Checks whether the device is locked. Returns: `True` if the device is locked """ ext_name = 'mobile: isLocked' try: return self.assert_extension_exists(ext_name).execute_script('mobile: isLocked') except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute(Command.IS_LOCKED)['value'] def shake(self) -> 'WebDriver': """Shake the device. Returns: Union['WebDriver', 'HardwareActions']: Self instance """ ext_name = 'mobile: shake' try: self.assert_extension_exists(ext_name).execute_script(ext_name) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.SHAKE) return cast('WebDriver', self) def touch_id(self, match: bool) -> 'WebDriver': """Simulate touchId on iOS Simulator Args: match: Simulates a successful touch (`True`) or a failed touch (`False`) Returns: Union['WebDriver', 'HardwareActions']: Self instance """ self.execute_script( 'mobile: sendBiometricMatch', { 'type': 'touchId', 'match': match, }, ) return cast('WebDriver', self) def toggle_touch_id_enrollment(self) -> 'WebDriver': """Toggle enroll touchId on iOS Simulator Returns: Union['WebDriver', 'HardwareActions']: Self instance """ is_enrolled = self.execute_script('mobile: isBiometricEnrolled') self.execute_script('mobile: enrollBiometric', {'isEnabled': not is_enrolled}) return cast('WebDriver', self) def finger_print(self, finger_id: int) -> 'WebDriver': """Authenticate users by using their finger print scans on supported Android emulators. Args: finger_id: Finger prints stored in Android Keystore system (from 1 to 10) """ ext_name = 'mobile: fingerprint' args = {'fingerprintId': finger_id} try: self.assert_extension_exists(ext_name).execute_script(ext_name, args) except UnknownMethodException: self.mark_extension_absence(ext_name).execute(Command.FINGER_PRINT, args) return cast('WebDriver', self) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.LOCK] = ('POST', '/session/$sessionId/appium/device/lock') commands[Command.UNLOCK] = ('POST', '/session/$sessionId/appium/device/unlock') commands[Command.IS_LOCKED] = ('POST', '/session/$sessionId/appium/device/is_locked') commands[Command.SHAKE] = ('POST', '/session/$sessionId/appium/device/shake') commands[Command.TOUCH_ID] = ('POST', '/session/$sessionId/appium/simulator/touch_id') commands[Command.TOGGLE_TOUCH_ID_ENROLLMENT] = ( 'POST', '/session/$sessionId/appium/simulator/toggle_touch_id_enrollment', ) commands[Command.FINGER_PRINT] = ( 'POST', '/session/$sessionId/appium/device/finger_print', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/hw_actions.py
hw_actions.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, Dict, Optional, cast from selenium.common.exceptions import UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from ..mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class Keyboard(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): def hide_keyboard( self, key_name: Optional[str] = None, key: Optional[str] = None, strategy: Optional[str] = None ) -> 'WebDriver': """Hides the software keyboard on the device. In iOS, use `key_name` to press a particular key, or `strategy`. In Android, no parameters are used. Args: key_name: key to press key: strategy: strategy for closing the keyboard (e.g., `tapOutside`) Returns: Union['WebDriver', 'Keyboard']: Self instance """ ext_name = 'mobile: hideKeyboard' try: self.assert_extension_exists(ext_name).execute_script( ext_name, {**({'keys': [key or key_name]} if key or key_name else {})} ) except UnknownMethodException: # TODO: Remove the fallback data: Dict[str, Optional[str]] = {} if key_name is not None: data['keyName'] = key_name elif key is not None: data['key'] = key elif strategy is None: strategy = 'tapOutside' data['strategy'] = strategy self.mark_extension_absence(ext_name).execute(Command.HIDE_KEYBOARD, data) return cast('WebDriver', self) def is_keyboard_shown(self) -> bool: """Attempts to detect whether a software keyboard is present Returns: `True` if keyboard is shown """ ext_name = 'mobile: isKeyboardShown' try: return self.assert_extension_exists(ext_name).execute_script(ext_name) except UnknownMethodException: return self.mark_extension_absence(ext_name).execute(Command.IS_KEYBOARD_SHOWN)['value'] def keyevent(self, keycode: int, metastate: Optional[int] = None) -> 'WebDriver': """Sends a keycode to the device. Android only. Possible keycodes can be found in http://developer.android.com/reference/android/view/KeyEvent.html. Args: keycode: the keycode to be sent to the device metastate: meta information about the keycode being sent Returns: Union['WebDriver', 'Keyboard']: Self instance """ return self.press_keycode(keycode=keycode, metastate=metastate) def press_keycode(self, keycode: int, metastate: Optional[int] = None, flags: Optional[int] = None) -> 'WebDriver': """Sends a keycode to the device. Android only. Possible keycodes can be found in http://developer.android.com/reference/android/view/KeyEvent.html. Args: keycode: the keycode to be sent to the device metastate: meta information about the keycode being sent flags: the set of key event flags Returns: Union['WebDriver', 'Keyboard']: Self instance """ ext_name = 'mobile: pressKey' args = {'keycode': keycode} if metastate is not None: args['metastate'] = metastate if flags is not None: args['flags'] = flags try: self.assert_extension_exists(ext_name).execute_script(ext_name, args) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.PRESS_KEYCODE, args) return cast('WebDriver', self) def long_press_keycode( self, keycode: int, metastate: Optional[int] = None, flags: Optional[int] = None ) -> 'WebDriver': """Sends a long press of keycode to the device. Android only. Possible keycodes can be found in http://developer.android.com/reference/android/view/KeyEvent.html. Args: keycode: the keycode to be sent to the device metastate: meta information about the keycode being sent flags: the set of key event flags Returns: Union['WebDriver', 'Keyboard']: Self instance """ ext_name = 'mobile: pressKey' args = {'keycode': keycode} if metastate is not None: args['metastate'] = metastate if flags is not None: args['flags'] = flags try: self.assert_extension_exists(ext_name).execute_script( ext_name, { **args, 'isLongPress': True, }, ) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.LONG_PRESS_KEYCODE, args) return cast('WebDriver', self) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.HIDE_KEYBOARD] = ( 'POST', '/session/$sessionId/appium/device/hide_keyboard', ) commands[Command.IS_KEYBOARD_SHOWN] = ( 'GET', '/session/$sessionId/appium/device/is_keyboard_shown', ) commands[Command.KEY_EVENT] = ('POST', '/session/$sessionId/appium/device/keyevent') commands[Command.PRESS_KEYCODE] = ( 'POST', '/session/$sessionId/appium/device/press_keycode', ) commands[Command.LONG_PRESS_KEYCODE] = ( 'POST', '/session/$sessionId/appium/device/long_press_keycode', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/keyboard.py
keyboard.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, Any, Dict, cast from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from ..mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class Settings(CanExecuteCommands): def get_settings(self) -> Dict[str, Any]: """Returns the appium server Settings for the current session. Do not get Settings confused with Desired Capabilities, they are separate concepts. See https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/settings.md Returns: Current settings """ return self.execute(Command.GET_SETTINGS, {})['value'] def update_settings(self, settings: Dict[str, Any]) -> 'WebDriver': """Set settings for the current session. For more on settings, see: https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/settings.md Args: settings: dictionary of settings to apply to the current test session """ self.execute(Command.UPDATE_SETTINGS, {"settings": settings}) return cast('WebDriver', self) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.GET_SETTINGS] = ('GET', '/session/$sessionId/appium/settings') commands[Command.UPDATE_SETTINGS] = ('POST', '/session/$sessionId/appium/settings')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/settings.py
settings.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, Dict, Union, cast from selenium.common.exceptions import UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from ..mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class Location(CanExecuteCommands, CanExecuteScripts): def toggle_location_services(self) -> 'WebDriver': """Toggle the location services on the device. This API only reliably since Android 12 (API level 31) Android only. Returns: Union['WebDriver', 'Location']: Self instance """ try: self.execute_script('mobile: toggleGps') except UnknownMethodException: # TODO: Remove the fallback self.execute(Command.TOGGLE_LOCATION_SERVICES) return cast('WebDriver', self) def set_location( self, latitude: Union[float, str], longitude: Union[float, str], altitude: Union[float, str, None] = None, speed: Union[float, str, None] = None, satellites: Union[float, str, None] = None, ) -> 'WebDriver': """Set the location of the device Args: latitude: String or numeric value between -90.0 and 90.00 longitude: String or numeric value between -180.0 and 180.0 altitude: String or numeric value (Android real device only) speed: String or numeric value larger than 0.0 (Android real devices only) satellites: String or numeric value of active GPS satellites in range 1..12. (Android emulators only) Returns: Union['WebDriver', 'Location']: Self instance """ data = { "location": { "latitude": latitude, "longitude": longitude, } } if altitude is not None: data['location']['altitude'] = altitude if speed is not None: data['location']['speed'] = speed if satellites is not None: data['location']['satellites'] = satellites self.execute(Command.SET_LOCATION, data) return cast('WebDriver', self) @property def location(self) -> Dict[str, float]: """Retrieves the current location Returns: A dictionary whose keys are - latitude (float) - longitude (float) - altitude (float) """ return self.execute(Command.GET_LOCATION)['value'] # pylint: disable=unsubscriptable-object def _add_commands(self) -> None: """Add location endpoints. They are not int w3c spec.""" # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.TOGGLE_LOCATION_SERVICES] = ( 'POST', '/session/$sessionId/appium/device/toggle_location_services', ) commands[Command.GET_LOCATION] = ('GET', '/session/$sessionId/location') commands[Command.SET_LOCATION] = ('POST', '/session/$sessionId/location')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/location.py
location.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Union from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from ..mobilecommand import MobileCommand as Command class ScreenRecord(CanExecuteCommands): def start_recording_screen(self, **options: Any) -> Union[bytes, str]: """Start asynchronous screen recording process. +--------------+-----+---------+-----+-------+ | Keyword Args | iOS | Android | Win | macOS | +==============+=====+=========+=====+=======+ | remotePath | O | O | O | O | +--------------+-----+---------+-----+-------+ | user | O | O | O | O | +--------------+-----+---------+-----+-------+ | password | O | O | O | O | +--------------+-----+---------+-----+-------+ | method | O | O | O | O | +--------------+-----+---------+-----+-------+ | timeLimit | O | O | O | O | +--------------+-----+---------+-----+-------+ | forceRestart | O | O | O | O | +--------------+-----+---------+-----+-------+ | fileFieldName| O | O | O | O | +--------------+-----+---------+-----+-------+ | formFields | O | O | O | O | +--------------+-----+---------+-----+-------+ | headers | O | O | O | O | +--------------+-----+---------+-----+-------+ | videoQuality | O | | | | +--------------+-----+---------+-----+-------+ | videoType | O | | | | +--------------+-----+---------+-----+-------+ | videoFps | O | | | | +--------------+-----+---------+-----+-------+ | videoFilter | O | | O | O | +--------------+-----+---------+-----+-------+ | videoScale | O | | | | +--------------+-----+---------+-----+-------+ | pixelFormat | O | | | | +--------------+-----+---------+-----+-------+ | videoSize | | O | | | +--------------+-----+---------+-----+-------+ | bitRate | | O | | | +--------------+-----+---------+-----+-------+ | bugReport | | O | | | +--------------+-----+---------+-----+-------+ | fps | | | O | O | +--------------+-----+---------+-----+-------+ | captureCursor| | | O | O | +--------------+-----+---------+-----+-------+ | captureClicks| | | O | O | +--------------+-----+---------+-----+-------+ | deviceId | | | | O | +--------------+-----+---------+-----+-------+ | preset | | | O | O | +--------------+-----+---------+-----+-------+ | audioInput | | | O | | +--------------+-----+---------+-----+-------+ Keyword Args: remotePath (str): The remotePath upload option is the path to the remote location, where the resulting video from the previous screen recording should be uploaded. The following protocols are supported: http/https (multipart), ftp. Missing value (the default setting) means the content of the resulting file should be encoded as Base64 and passed as the endpoint response value, but an exception will be thrown if the generated media file is too big to fit into the available process memory. This option only has an effect if there is/was an active screen recording session and forced restart is not enabled (the default setting). user (str): The name of the user for the remote authentication. Only has an effect if both `remotePath` and `password` are set. password (str): The password for the remote authentication. Only has an effect if both `remotePath` and `user` are set. method (str): The HTTP method name ('PUT'/'POST'). PUT method is used by default. Only has an effect if `remotePath` is set. timeLimit (int): The actual time limit of the recorded video in seconds. The default value for both iOS and Android is 180 seconds (3 minutes). The default value for macOS is 600 seconds (10 minutes). The maximum value for Android is 3 minutes. The maximum value for iOS is 10 minutes. The maximum value for macOS is 10000 seconds (166 minutes). forcedRestart (bool): Whether to ignore the result of previous capture and start a new recording immediately (`True` value). By default (`False`) the endpoint will try to catch and return the result of the previous capture if it's still available. fileFieldName (str): [multipart/form-data requests] The name of the form field containing the binary payload. "file" by default. (Since Appium 1.18.0) formFields (dict): [multipart/form-data requests] Additional form fields mapping. If any entry has the same key as `fileFieldName` then it is going to be ignored. (Since Appium 1.18.0) headers (dict): [multipart/form-data requests] Headers mapping (Since Appium 1.18.0) videoQuality (str): [iOS] The video encoding quality: 'low', 'medium', 'high', 'photo'. Defaults to 'medium'. videoType (str): [iOS] The format of the screen capture to be recorded. Available formats: Execute `ffmpeg -codecs` in the terminal to see the list of supported video codecs. 'mjpeg' by default. (Since Appium 1.10.0) videoFps (int): [iOS] The Frames Per Second rate of the recorded video. Change this value if the resulting video is too slow or too fast. Defaults to 10. This can decrease the resulting file size. videoFilters (str): [iOS, Win, macOS] The FFMPEG video filters to apply. These filters allow to scale, flip, rotate and do many other useful transformations on the source video stream. The format of the property must comply with https://ffmpeg.org/ffmpeg-filters.html. (Since Appium 1.15) videoScale (str): [iOS] The scaling value to apply. Read https://trac.ffmpeg.org/wiki/Scaling for possible values. No scale is applied by default. If videoFilters are set then the scale setting is effectively ignored. (Since Appium 1.10.0) pixelFormat (str): [iOS] Output pixel format. Run `ffmpeg -pix_fmts` to list possible values. For Quicktime compatibility, set to "yuv420p" along with videoType: "libx264". (Since Appium 1.12.0) videoSize (str): [Android] The video size of the generated media file. The format is WIDTHxHEIGHT. The default value is the device's native display resolution (if supported), 1280x720 if not. For best results, use a size supported by your device's Advanced Video Coding (AVC) encoder. bitRate (int): [Android] The video bit rate for the video, in megabits per second. The default value is 4. You can increase the bit rate to improve video quality, but doing so results in larger movie files. bugReport (str): [Android] Makes the recorder to display an additional information on the video overlay, such as a timestamp, that is helpful in videos captured to illustrate bugs. This option is only supported since API level 27 (Android P). fps (int): [Win, macOS] The count of frames per second in the resulting video. Increasing fps value also increases the size of the resulting video file and the CPU usage. captureCursor (bool): [Win, macOS] Whether to capture the mouse cursor while recording the screen. Disabled by default. captureClick (bool): [Win, macOS] Whether to capture the click gestures while recording the screen. Disabled by default. deviceId (int): [macOS] Screen device index to use for the recording. The list of available devices could be retrieved using `ffmpeg -f avfoundation -list_devices true -i` command. This option is mandatory and must be always provided. preset (str): [Win, macOS] A preset is a collection of options that will provide a certain encoding speed to compression ratio. A slower preset will provide better compression (compression is quality per filesize). This means that, for example, if you target a certain file size or constant bit rate, you will achieve better quality with a slower preset. Read https://trac.ffmpeg.org/wiki/Encode/H.264 for more details. Possible values are 'ultrafast', 'superfast', 'veryfast'(default), 'faster', 'fast', 'medium', 'slow', 'slower', 'veryslow' Returns: bytes: Base-64 encoded content of the recorded media if `stop_recording_screen` isn't called after previous `start_recording_screen`. Otherwise returns an empty string. """ if 'password' in options: options['pass'] = options['password'] del options['password'] return self.execute(Command.START_RECORDING_SCREEN, {'options': options})['value'] def stop_recording_screen(self, **options: Any) -> bytes: """Gather the output from the previously started screen recording to a media file. Keyword Args: remotePath (str): The remotePath upload option is the path to the remote location, where the resulting video should be uploaded. The following protocols are supported: http/https (multipart), ftp. Missing value (the default setting) means the content of the resulting file should be encoded as Base64 and passed as the endpoint response value, but an exception will be thrown if the generated media file is too big to fit into the available process memory. user (str): The name of the user for the remote authentication. Only has an effect if both `remotePath` and `password` are set. password (str): The password for the remote authentication. Only has an effect if both `remotePath` and `user` are set. method (str): The HTTP method name ('PUT'/'POST'). PUT method is used by default. Only has an effect if `remotePath` is set. fileFieldName (str): [multipart/form-data requests] The name of the form field containing the binary payload. "file" by default. (Since Appium 1.18.0) formFields (dict): [multipart/form-data requests] Additional form fields mapping. If any entry has the same key as `fileFieldName` then it is going to be ignored. (Since Appium 1.18.0) headers (dict): [multipart/form-data requests] Headers mapping (Since Appium 1.18.0) Returns: bytes: Base-64 encoded content of the recorded media file or an empty string if the file has been successfully uploaded to a remote location (depends on the actual `remotePath` value). """ if 'password' in options: options['pass'] = options['password'] del options['password'] return self.execute(Command.STOP_RECORDING_SCREEN, {'options': options})['value'] def _add_commands(self) -> None: # noinspection PyProtectedMember commands = self.command_executor._commands commands[Command.START_RECORDING_SCREEN] = ( 'POST', '/session/$sessionId/appium/start_recording_screen', ) commands[Command.STOP_RECORDING_SCREEN] = ( 'POST', '/session/$sessionId/appium/stop_recording_screen', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/screen_record.py
screen_record.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import Any, Dict, List from appium.common.logger import logger from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from ..mobilecommand import MobileCommand as Command class Session(CanExecuteCommands): @property def session(self) -> Dict[str, Any]: """Retrieves session information from the current session deprecated:: 2.0.0 Usage: session = driver.session Returns: `dict`: containing information from the current session """ warnings.warn( 'The "session" API is deprecated and will be removed in future versions', DeprecationWarning, ) return self.execute(Command.GET_SESSION)['value'] @property def all_sessions(self) -> List[Dict[str, Any]]: """Retrieves all sessions that are open deprecated:: 2.0.0 Usage: sessions = driver.all_sessions Returns: :obj:`list` of :obj:`dict`: containing all open sessions """ warnings.warn( 'The "all_sessions" API is deprecated and will be removed in future versions', DeprecationWarning, ) return self.execute(Command.GET_ALL_SESSIONS)['value'] @property def events(self) -> Dict: """Retrieves events information from the current session Usage: events = driver.events Returns: `dict`: containing events timing information from the current session """ try: session = self.session return session['events'] except Exception as e: logger.warning('Could not find events information in the session. Error: %s', e) return {} def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.GET_SESSION] = ('GET', '/session/$sessionId') commands[Command.GET_ALL_SESSIONS] = ('GET', '/sessions')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/session.py
session.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 from typing import TYPE_CHECKING, Optional, cast from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.webdriver.clipboard_content_type import ClipboardContentType from ..mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class Clipboard(CanExecuteCommands): def set_clipboard( self, content: bytes, content_type: str = ClipboardContentType.PLAINTEXT, label: Optional[str] = None ) -> 'WebDriver': """Set the content of the system clipboard Args: content: The content to be set as bytearray string content_type: One of ClipboardContentType items. Only ClipboardContentType.PLAINTEXT is supported on Android label: label argument, which only works for Android Returns: Union['WebDriver', 'Clipboard']: Self instance """ options = { 'content': base64.b64encode(content).decode('UTF-8'), 'contentType': content_type, } if label: options['label'] = label self.execute(Command.SET_CLIPBOARD, options) return cast('WebDriver', self) def set_clipboard_text(self, text: str, label: Optional[str] = None) -> 'WebDriver': """Copies the given text to the system clipboard Args: text: The text to be set label:label argument, which only works for Android Returns: Union['WebDriver', 'Clipboard']: Self instance """ return self.set_clipboard(bytes(str(text), 'UTF-8'), ClipboardContentType.PLAINTEXT, label) def get_clipboard(self, content_type: str = ClipboardContentType.PLAINTEXT) -> bytes: """Receives the content of the system clipboard Args: content_type: One of ClipboardContentType items. Only ClipboardContentType.PLAINTEXT is supported on Android Returns: base64-encoded string: Clipboard content. Or return an empty string if the clipboard is empty """ base64_str = self.execute(Command.GET_CLIPBOARD, {'contentType': content_type})['value'] return base64.b64decode(base64_str) def get_clipboard_text(self) -> str: """Receives the text of the system clipboard Returns: The actual clipboard text or an empty string if the clipboard is empty """ return self.get_clipboard(ClipboardContentType.PLAINTEXT).decode('UTF-8') def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.SET_CLIPBOARD] = ( 'POST', '/session/$sessionId/appium/device/set_clipboard', ) commands[Command.GET_CLIPBOARD] = ( 'POST', '/session/$sessionId/appium/device/get_clipboard', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/clipboard.py
clipboard.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import TYPE_CHECKING, Any, Dict, Union, cast from selenium.common.exceptions import InvalidArgumentException, UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from ..mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class Applications(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): def background_app(self, seconds: int) -> 'WebDriver': """Puts the application in the background on the device for a certain duration. Args: seconds: the duration for the application to remain in the background. Providing a negative value will continue immediately after putting the app under test to the background. Returns: Union['WebDriver', 'Applications']: Self instance """ ext_name = 'mobile: backgroundApp' args = {'seconds': seconds} try: self.assert_extension_exists(ext_name).execute_script(ext_name, args) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.BACKGROUND, args) return cast('WebDriver', self) def is_app_installed(self, bundle_id: str) -> bool: """Checks whether the application specified by `bundle_id` is installed on the device. Args: bundle_id: the id of the application to query Returns: `True` if app is installed """ ext_name = 'mobile: isAppInstalled' try: return self.assert_extension_exists(ext_name).execute_script( ext_name, { 'bundleId': bundle_id, 'appId': bundle_id, }, ) except (UnknownMethodException, InvalidArgumentException): # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute( Command.IS_APP_INSTALLED, { 'bundleId': bundle_id, }, )['value'] def install_app(self, app_path: str, **options: Any) -> 'WebDriver': """Install the application found at `app_path` on the device. Args: app_path: the local or remote path to the application to install Keyword Args: replace (bool): [Android only] whether to reinstall/upgrade the package if it is already present on the device under test. True by default timeout (int): [Android only] how much time to wait for the installation to complete. 60000ms by default. allowTestPackages (bool): [Android only] whether to allow installation of packages marked as test in the manifest. False by default useSdcard (bool): [Android only] whether to use the SD card to install the app. False by default grantPermissions (bool): [Android only] whether to automatically grant application permissions on Android 6+ after the installation completes. False by default Returns: Union['WebDriver', 'Applications']: Self instance """ ext_name = 'mobile: installApp' try: self.assert_extension_exists(ext_name).execute_script( 'mobile: installApp', { 'app': app_path, 'appPath': app_path, **(options or {}), }, ) except (UnknownMethodException, InvalidArgumentException): # TODO: Remove the fallback data: Dict[str, Any] = {'appPath': app_path} if options: data.update({'options': options}) self.mark_extension_absence(ext_name).execute(Command.INSTALL_APP, data) return cast('WebDriver', self) def remove_app(self, app_id: str, **options: Any) -> 'WebDriver': """Remove the specified application from the device. Args: app_id: the application id to be removed Keyword Args: keepData (bool): [Android only] whether to keep application data and caches after it is uninstalled. False by default timeout (int): [Android only] how much time to wait for the uninstall to complete. 20000ms by default. Returns: Union['WebDriver', 'Applications']: Self instance """ ext_name = 'mobile: removeApp' try: self.assert_extension_exists(ext_name).execute_script( ext_name, { 'appId': app_id, 'bundleId': app_id, **(options or {}), }, ) except (UnknownMethodException, InvalidArgumentException): # TODO: Remove the fallback data: Dict[str, Any] = {'appId': app_id} if options: data.update({'options': options}) self.mark_extension_absence(ext_name).execute(Command.REMOVE_APP, data) return cast('WebDriver', self) def launch_app(self) -> 'WebDriver': """Start on the device the application specified in the desired capabilities. deprecated:: 2.0.0 Returns: Union['WebDriver', 'Applications']: Self instance """ warnings.warn( 'The "launchApp" API is deprecated and will be removed in future versions. ' 'See https://github.com/appium/appium/issues/15807', DeprecationWarning, ) self.execute(Command.LAUNCH_APP) return cast('WebDriver', self) def close_app(self) -> 'WebDriver': """Stop the running application, specified in the desired capabilities, on the device. deprecated:: 2.0.0 Returns: Union['WebDriver', 'Applications']: Self instance """ warnings.warn( 'The "closeApp" API is deprecated and will be removed in future versions. ' 'See https://github.com/appium/appium/issues/15807', DeprecationWarning, ) self.execute(Command.CLOSE_APP) return cast('WebDriver', self) def terminate_app(self, app_id: str, **options: Any) -> bool: """Terminates the application if it is running. Args: app_id: the application id to be terminates Keyword Args: `timeout` (int): [Android only] how much time to wait for the uninstall to complete. 500ms by default. Returns: True if the app has been successfully terminated """ ext_name = 'mobile: terminateApp' try: return self.assert_extension_exists(ext_name).execute_script( ext_name, { 'appId': app_id, 'bundleId': app_id, **(options or {}), }, ) except (UnknownMethodException, InvalidArgumentException): # TODO: Remove the fallback data: Dict[str, Any] = {'appId': app_id} if options: data.update({'options': options}) return self.mark_extension_absence(ext_name).execute(Command.TERMINATE_APP, data)['value'] def activate_app(self, app_id: str) -> 'WebDriver': """Activates the application if it is not running or is running in the background. Args: app_id: the application id to be activated Returns: Union['WebDriver', 'Applications']: Self instance """ ext_name = 'mobile: activateApp' try: self.assert_extension_exists(ext_name).execute_script( ext_name, { 'appId': app_id, 'bundleId': app_id, }, ) except (UnknownMethodException, InvalidArgumentException): # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.ACTIVATE_APP, {'appId': app_id}) return cast('WebDriver', self) def query_app_state(self, app_id: str) -> int: """Queries the state of the application. Args: app_id: the application id to be queried Returns: One of possible application state constants. See ApplicationState class for more details. """ ext_name = 'mobile: queryAppState' try: return self.assert_extension_exists(ext_name).execute_script( ext_name, { 'appId': app_id, 'bundleId': app_id, }, ) except (UnknownMethodException, InvalidArgumentException): # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute( Command.QUERY_APP_STATE, { 'appId': app_id, }, )['value'] def app_strings(self, language: Union[str, None] = None, string_file: Union[str, None] = None) -> Dict[str, str]: """Returns the application strings from the device for the specified language. Args: language: strings language code string_file: the name of the string file to query. Only relevant for XCUITest driver Returns: The key is string id and the value is the content. """ ext_name = 'mobile: getAppStrings' data = {} if language is not None: data['language'] = language if string_file is not None: data['stringFile'] = string_file try: return self.assert_extension_exists(ext_name).execute_script(ext_name, data) except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute(Command.GET_APP_STRINGS, data)['value'] def reset(self) -> 'WebDriver': """Resets the current application on the device. deprecated:: 2.0.0 Returns: Union['WebDriver', 'Applications']: Self instance """ warnings.warn( 'The "reset" API is deprecated and will be removed in future versions. ' 'See https://github.com/appium/appium/issues/15807', DeprecationWarning, ) self.execute(Command.RESET) return cast('WebDriver', self) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.BACKGROUND] = ('POST', '/session/$sessionId/appium/app/background') commands[Command.IS_APP_INSTALLED] = ( 'POST', '/session/$sessionId/appium/device/app_installed', ) commands[Command.INSTALL_APP] = ('POST', '/session/$sessionId/appium/device/install_app') commands[Command.REMOVE_APP] = ('POST', '/session/$sessionId/appium/device/remove_app') commands[Command.TERMINATE_APP] = ( 'POST', '/session/$sessionId/appium/device/terminate_app', ) commands[Command.ACTIVATE_APP] = ( 'POST', '/session/$sessionId/appium/device/activate_app', ) commands[Command.QUERY_APP_STATE] = ( 'POST', '/session/$sessionId/appium/device/app_state', ) commands[Command.GET_APP_STRINGS] = ('POST', '/session/$sessionId/appium/app/strings') commands[Command.RESET] = ('POST', '/session/$sessionId/appium/app/reset') commands[Command.LAUNCH_APP] = ('POST', '/session/$sessionId/appium/app/launch') commands[Command.CLOSE_APP] = ('POST', '/session/$sessionId/appium/app/close')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/applications.py
applications.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import TYPE_CHECKING, List, cast from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from ..mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class IME(CanExecuteCommands): @property def available_ime_engines(self) -> List[str]: """Get the available input methods for an Android device. Package and activity are returned (e.g., ['com.android.inputmethod.latin/.LatinIME']) Android only. deprecated:: 2.0.0 Returns: :obj:`list` of :obj:`str`: The available input methods for an Android device """ warnings.warn( 'The "available_ime_engines" API is deprecated and will be removed in future versions. ' 'Use "mobile: shell" extension instead', DeprecationWarning, ) return self.execute(Command.GET_AVAILABLE_IME_ENGINES, {})['value'] # pylint: disable=unsubscriptable-object def is_ime_active(self) -> bool: """Checks whether the device has IME service active. Android only. deprecated:: 2.0.0 Returns: `True` if IME service is active """ warnings.warn( 'The "is_ime_active" API is deprecated and will be removed in future versions. ' 'Use "mobile: shell" extension instead', DeprecationWarning, ) return self.execute(Command.IS_IME_ACTIVE, {})['value'] # pylint: disable=unsubscriptable-object def activate_ime_engine(self, engine: str) -> 'WebDriver': """Activates the given IME engine on the device. Android only. deprecated:: 2.0.0 Args: engine: the package and activity of the IME engine to activate (e.g., 'com.android.inputmethod.latin/.LatinIME') Returns: Union['WebDriver', 'IME']: Self instance """ warnings.warn( 'The "activate_ime_engine" API is deprecated and will be removed in future versions. ' 'Use "mobile: shell" extension instead', DeprecationWarning, ) data = {'engine': engine} self.execute(Command.ACTIVATE_IME_ENGINE, data) return cast('WebDriver', self) def deactivate_ime_engine(self) -> 'WebDriver': """Deactivates the currently active IME engine on the device. Android only. deprecated:: 2.0.0 Returns: Union['WebDriver', 'IME']: Self instance """ warnings.warn( 'The "deactivate_ime_engine" API is deprecated and will be removed in future versions. ' 'Use "mobile: shell" extension instead', DeprecationWarning, ) self.execute(Command.DEACTIVATE_IME_ENGINE, {}) return cast('WebDriver', self) @property def active_ime_engine(self) -> str: """Returns the activity and package of the currently active IME engine (e.g., 'com.android.inputmethod.latin/.LatinIME'). Android only. deprecated:: 2.0.0 Returns: str: The activity and package of the currently active IME engine """ warnings.warn( 'The "active_ime_engine" API is deprecated and will be removed in future versions. ' 'Use "mobile: shell" extension instead', DeprecationWarning, ) return self.execute(Command.GET_ACTIVE_IME_ENGINE, {})['value'] # pylint: disable=unsubscriptable-object def _add_commands(self) -> None: """Add IME commands. They are not in W3C spec.""" # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.GET_AVAILABLE_IME_ENGINES] = ( 'GET', '/session/$sessionId/ime/available_engines', ) commands[Command.IS_IME_ACTIVE] = ('GET', '/session/$sessionId/ime/activated') commands[Command.ACTIVATE_IME_ENGINE] = ('POST', '/session/$sessionId/ime/activate') commands[Command.DEACTIVATE_IME_ENGINE] = ('POST', '/session/$sessionId/ime/deactivate') commands[Command.GET_ACTIVE_IME_ENGINE] = ( 'GET', '/session/$sessionId/ime/active_engine', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/ime.py
ime.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, Dict, List, Union, cast from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from ..mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class LogEvent(CanExecuteCommands): def get_events(self, type: Union[List[str], None] = None) -> Dict[str, Union[str, int]]: """Retrieves events information from the current session (Since Appium 1.16.0) Args: type: The event type to filter with Usage: | events = driver.get_events() | events = driver.get_events(['appium:funEvent']) Returns: `dict`: A dictionary of events timing information containing the following entries | commands: (`list` of `dict`) List of dictionaries containing the following entries | cmd: The command name that has been sent to the appium server | startTime: Received time | endTime: Response time """ data = {} if type is not None: data['type'] = type return self.execute(Command.GET_EVENTS, data)['value'] def log_event(self, vendor: str, event: str) -> 'WebDriver': """Log a custom event on the Appium server. (Since Appium 1.16.0) Args: vendor: The vendor to log event: The event to log Usage: driver.log_event('appium', 'funEvent') Returns: Union['WebDriver', 'LogEvent']: Self instance """ data = {'vendor': vendor, 'event': event} self.execute(Command.LOG_EVENT, data) return cast('WebDriver', self) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.GET_EVENTS] = ('POST', '/session/$sessionId/appium/events') commands[Command.LOG_EVENT] = ('POST', '/session/$sessionId/appium/log_event')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/log_event.py
log_event.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, Any, Dict, cast from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class ExecuteMobileCommand(CanExecuteScripts): def press_button(self, button_name: str) -> 'WebDriver': """Sends a physical button name to the device to simulate the user pressing. iOS only. Possible button names can be found in https://github.com/appium/WebDriverAgent/blob/master/WebDriverAgentLib/Categories/XCUIDevice%2BFBHelpers.h Args: button_name: the button name to be sent to the device Returns: Union['WebDriver', 'ExecuteMobileCommand']: Self instance """ data = {'name': button_name} self.execute_script('mobile: pressButton', data) return cast('WebDriver', self) @property def battery_info(self) -> Dict[str, Any]: """Retrieves battery information for the device under test. Returns: `dict`: containing the following entries level: Battery level in range [0.0, 1.0], where 1.0 means 100% charge. Any value lower than 0 means the level cannot be retrieved state: Platform-dependent battery state value. On iOS (XCUITest): 1: Unplugged 2: Charging 3: Full Any other value means the state cannot be retrieved On Android (UIAutomator2): 2: Charging 3: Discharging 4: Not charging 5: Full Any other value means the state cannot be retrieved """ return self.execute_script('mobile: batteryInfo')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/execute_mobile_command.py
execute_mobile_command.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from selenium.common.exceptions import UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from ..mobilecommand import MobileCommand as Command class DeviceTime(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): @property def device_time(self) -> str: """Returns the date and time from the device. Return: str: The date and time """ ext_name = 'mobile: getDeviceTime' try: return self.assert_extension_exists(ext_name).execute_script(ext_name) except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute(Command.GET_DEVICE_TIME_GET, {})['value'] def get_device_time(self, format: Optional[str] = None) -> str: """Returns the date and time from the device. Args: format: The set of format specifiers. Read https://momentjs.com/docs/ to get the full list of supported datetime format specifiers. If unset, return :func:`.device_time` as default format is `YYYY-MM-DDTHH:mm:ssZ`, which complies to ISO-8601 Usage: | self.driver.get_device_time() | self.driver.get_device_time("YYYY-MM-DD") Return: str: The date and time """ ext_name = 'mobile: getDeviceTime' if format is None: return self.device_time try: return self.assert_extension_exists(ext_name).execute_script(ext_name, {'format': format}) except UnknownMethodException: return self.mark_extension_absence(ext_name).execute(Command.GET_DEVICE_TIME_POST, {'format': format})[ 'value' ] def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.GET_DEVICE_TIME_GET] = ( 'GET', '/session/$sessionId/appium/device/system_time', ) commands[Command.GET_DEVICE_TIME_POST] = ( 'POST', '/session/$sessionId/appium/device/system_time', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/device_time.py
device_time.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, List, Optional, Tuple, cast from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.actions import interaction from selenium.webdriver.common.actions.action_builder import ActionBuilder from selenium.webdriver.common.actions.mouse_button import MouseButton from selenium.webdriver.common.actions.pointer_input import PointerInput from appium.webdriver.webelement import WebElement if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class ActionHelpers: def scroll(self, origin_el: WebElement, destination_el: WebElement, duration: Optional[int] = None) -> 'WebDriver': """Scrolls from one element to another Args: origin_el: the element from which to begin scrolling (center of element) destination_el: the element to scroll to (center of element) duration: defines speed of scroll action when moving from originalEl to destinationEl. Default is 600 ms for W3C spec. Usage: driver.scroll(el1, el2) Returns: Union['WebDriver', 'ActionHelpers']: Self instance """ # XCUITest x W3C spec has no duration by default in server side if duration is None: duration = 600 touch_input = PointerInput(interaction.POINTER_TOUCH, "touch") actions = ActionChains(self) actions.w3c_actions = ActionBuilder(self, mouse=touch_input) # https://github.com/SeleniumHQ/selenium/blob/3c82c868d4f2a7600223a1b3817301d0b04d28e4/py/selenium/webdriver/common/actions/pointer_actions.py#L83 actions.w3c_actions.pointer_action.move_to(origin_el) actions.w3c_actions.pointer_action.pointer_down() # setup duration for second move only, assuming duration always has atleast default value actions.w3c_actions = ActionBuilder(self, mouse=touch_input, duration=duration) actions.w3c_actions.pointer_action.move_to(destination_el) actions.w3c_actions.pointer_action.release() actions.perform() return cast('WebDriver', self) def drag_and_drop(self, origin_el: WebElement, destination_el: WebElement) -> 'WebDriver': """Drag the origin element to the destination element Args: origin_el: the element to drag destination_el: the element to drag to Returns: Union['WebDriver', 'ActionHelpers']: Self instance """ actions = ActionChains(self) # 'mouse' pointer action actions.w3c_actions.pointer_action.click_and_hold(origin_el) actions.w3c_actions.pointer_action.move_to(destination_el) actions.w3c_actions.pointer_action.release() actions.perform() return cast('WebDriver', self) def tap(self, positions: List[Tuple[int, int]], duration: Optional[int] = None) -> 'WebDriver': """Taps on an particular place with up to five fingers, holding for a certain time Args: positions: an array of tuples representing the x/y coordinates of the fingers to tap. Length can be up to five. duration: length of time to tap, in ms Usage: driver.tap([(100, 20), (100, 60), (100, 100)], 500) Returns: Union['WebDriver', 'ActionHelpers']: Self instance """ if len(positions) == 1: actions = ActionChains(self) actions.w3c_actions = ActionBuilder(self, mouse=PointerInput(interaction.POINTER_TOUCH, "touch")) x = positions[0][0] y = positions[0][1] actions.w3c_actions.pointer_action.move_to_location(x, y) actions.w3c_actions.pointer_action.pointer_down() if duration: actions.w3c_actions.pointer_action.pause(duration / 1000) else: actions.w3c_actions.pointer_action.pause(0.1) actions.w3c_actions.pointer_action.release() actions.perform() else: finger = 0 actions = ActionChains(self) actions.w3c_actions.devices = [] for position in positions: finger += 1 x = position[0] y = position[1] # https://github.com/SeleniumHQ/selenium/blob/trunk/py/selenium/webdriver/common/actions/pointer_input.py new_input = actions.w3c_actions.add_pointer_input('touch', f'finger{finger}') new_input.create_pointer_move(x=x, y=y) new_input.create_pointer_down(button=MouseButton.LEFT) if duration: new_input.create_pause(duration / 1000) else: new_input.create_pause(0.1) new_input.create_pointer_up(MouseButton.LEFT) actions.perform() return cast('WebDriver', self) def swipe(self, start_x: int, start_y: int, end_x: int, end_y: int, duration: int = 0) -> 'WebDriver': """Swipe from one point to another point, for an optional duration. Args: start_x: x-coordinate at which to start start_y: y-coordinate at which to start end_x: x-coordinate at which to stop end_y: y-coordinate at which to stop duration: defines the swipe speed as time taken to swipe from point a to point b, in ms. Usage: driver.swipe(100, 100, 100, 400) Returns: Union['WebDriver', 'ActionHelpers']: Self instance """ touch_input = PointerInput(interaction.POINTER_TOUCH, "touch") actions = ActionChains(self) actions.w3c_actions = ActionBuilder(self, mouse=touch_input) actions.w3c_actions.pointer_action.move_to_location(start_x, start_y) actions.w3c_actions.pointer_action.pointer_down() if duration > 0: actions.w3c_actions = ActionBuilder(self, mouse=touch_input, duration=duration) actions.w3c_actions.pointer_action.move_to_location(end_x, end_y) actions.w3c_actions.pointer_action.release() actions.perform() return cast('WebDriver', self) def flick(self, start_x: int, start_y: int, end_x: int, end_y: int) -> 'WebDriver': """Flick from one point to another point. Args: start_x: x-coordinate at which to start start_y: y-coordinate at which to start end_x: x-coordinate at which to stop end_y: y-coordinate at which to stop Usage: driver.flick(100, 100, 100, 400) Returns: Union['WebDriver', 'ActionHelpers']: Self instance """ actions = ActionChains(self) actions.w3c_actions = ActionBuilder(self, mouse=PointerInput(interaction.POINTER_TOUCH, "touch")) actions.w3c_actions.pointer_action.move_to_location(start_x, start_y) actions.w3c_actions.pointer_action.pointer_down() actions.w3c_actions.pointer_action.move_to_location(end_x, end_y) actions.w3c_actions.pointer_action.release() actions.perform() return cast('WebDriver', self)
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/action_helpers.py
action_helpers.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import TYPE_CHECKING, Any, cast from selenium.common.exceptions import UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from appium.webdriver.mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class Common(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): def end_test_coverage(self, intent: str, path: str) -> Any: """Ends the coverage collection and pull the coverage.ec file from the device. deprecated:: 2.9.0 Android only. See https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/android/android-coverage.md Args: intent: description of operation to be performed path: path to coverage.ec file to be pulled from the device Returns: TODO """ warnings.warn( 'This API is deprecated and will be removed in future versions', DeprecationWarning, ) return self.execute( Command.END_TEST_COVERAGE, { 'intent': intent, 'path': path, }, )['value'] def open_notifications(self) -> 'WebDriver': """Open notification shade in Android (API Level 18 and above) Returns: Union['WebDriver', 'Common']: Self instance """ ext_name = 'mobile: openNotifications' try: self.assert_extension_exists(ext_name).execute_script(ext_name) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.OPEN_NOTIFICATIONS, {}) return cast('WebDriver', self) @property def current_package(self) -> str: """Retrieves the current package running on the device.""" ext_name = 'mobile: getCurrentPackage' try: return self.assert_extension_exists(ext_name).execute_script(ext_name) except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute(Command.GET_CURRENT_PACKAGE)['value'] def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.GET_CURRENT_PACKAGE] = ( 'GET', '/session/$sessionId/appium/device/current_package', ) commands[Command.END_TEST_COVERAGE] = ( 'POST', '/session/$sessionId/appium/app/end_test_coverage', ) commands[Command.OPEN_NOTIFICATIONS] = ( 'POST', '/session/$sessionId/appium/device/open_notifications', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/android/common.py
common.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, cast from selenium.common.exceptions import UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from appium.webdriver.mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class Power(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): AC_OFF, AC_ON = 'off', 'on' def set_power_capacity(self, percent: int) -> 'WebDriver': """Emulate power capacity change on the connected emulator. Android only. Args: percent: The power capacity to be set. Can be set from 0 to 100 Usage: self.driver.set_power_capacity(50) Returns: Union['WebDriver', 'Power']: Self instance """ ext_name = 'mobile: powerCapacity' args = {'percent': percent} try: self.assert_extension_exists(ext_name).execute_script(ext_name, args) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.SET_POWER_CAPACITY, args) return cast('WebDriver', self) def set_power_ac(self, ac_state: str) -> 'WebDriver': """Emulate power state change on the connected emulator. Android only. Args: ac_state: The power ac state to be set. Use `Power.AC_OFF`, `Power.AC_ON` Usage: | self.driver.set_power_ac(Power.AC_OFF) | self.driver.set_power_ac(Power.AC_ON) Returns: Union['WebDriver', 'Power']: Self instance """ ext_name = 'mobile: powerAC' args = {'state': ac_state} try: self.assert_extension_exists(ext_name).execute_script(ext_name, args) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.SET_POWER_AC, args) return cast('WebDriver', self) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.SET_POWER_CAPACITY] = ( 'POST', '/session/$sessionId/appium/device/power_capacity', ) commands[Command.SET_POWER_AC] = ('POST', '/session/$sessionId/appium/device/power_ac')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/android/power.py
power.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class AndroidKey: # Key code constant: Unknown key code. UNKNOWN = 0 # Key code constant: Soft Left key. # Usually situated below the display on phones and used as a multi-function # feature key for selecting a software defined function shown on the bottom left # of the display. SOFT_LEFT = 1 # Key code constant: Soft Right key. # Usually situated below the display on phones and used as a multi-function # feature key for selecting a software defined function shown on the bottom right # of the display. SOFT_RIGHT = 2 # Key code constant: Home key. # This key is handled by the framework and is never delivered to applications. HOME = 3 # Key code constant: Back key. BACK = 4 # Key code constant: Call key. CALL = 5 # Key code constant: End Call key. ENDCALL = 6 # Key code constant: '0' key. DIGIT_0 = 7 # Key code constant: '1' key. DIGIT_1 = 8 # Key code constant: '2' key. DIGIT_2 = 9 # Key code constant: '3' key. DIGIT_3 = 10 # Key code constant: '4' key. DIGIT_4 = 11 # Key code constant: '5' key. DIGIT_5 = 12 # Key code constant: '6' key. DIGIT_6 = 13 # Key code constant: '7' key. DIGIT_7 = 14 # Key code constant: '8' key. DIGIT_8 = 15 # Key code constant: '9' key. DIGIT_9 = 16 # Key code constant: '*' key. STAR = 17 # Key code constant: '#' key. POUND = 18 # Key code constant: Directional Pad Up key. # May also be synthesized from trackball motions. DPAD_UP = 19 # Key code constant: Directional Pad Down key. # May also be synthesized from trackball motions. DPAD_DOWN = 20 # Key code constant: Directional Pad Left key. # May also be synthesized from trackball motions. DPAD_LEFT = 21 # Key code constant: Directional Pad Right key. # May also be synthesized from trackball motions. DPAD_RIGHT = 22 # Key code constant: Directional Pad Center key. # May also be synthesized from trackball motions. DPAD_CENTER = 23 # Key code constant: Volume Up key. # Adjusts the speaker volume up. VOLUME_UP = 24 # Key code constant: Volume Down key. # Adjusts the speaker volume down. VOLUME_DOWN = 25 # Key code constant: Power key. POWER = 26 # Key code constant: Camera key. # Used to launch a camera application or take pictures. CAMERA = 27 # Key code constant: Clear key. CLEAR = 28 # Key code constant: 'A' key. A = 29 # Key code constant: 'B' key. B = 30 # Key code constant: 'C' key. C = 31 # Key code constant: 'D' key. D = 32 # Key code constant: 'E' key. E = 33 # Key code constant: 'F' key. F = 34 # Key code constant: 'G' key. G = 35 # Key code constant: 'H' key. H = 36 # Key code constant: 'I' key. I = 37 # Key code constant: 'J' key. J = 38 # Key code constant: 'K' key. K = 39 # Key code constant: 'L' key. L = 40 # Key code constant: 'M' key. M = 41 # Key code constant: 'N' key. N = 42 # Key code constant: 'O' key. O = 43 # Key code constant: 'P' key. P = 44 # Key code constant: 'Q' key. Q = 45 # Key code constant: 'R' key. R = 46 # Key code constant: 'S' key. S = 47 # Key code constant: 'T' key. T = 48 # Key code constant: 'U' key. U = 49 # Key code constant: 'V' key. V = 50 # Key code constant: 'W' key. W = 51 # Key code constant: 'X' key. X = 52 # Key code constant: 'Y' key. Y = 53 # Key code constant: 'Z' key. Z = 54 # Key code constant: ',' key. COMMA = 55 # Key code constant: '.' key. PERIOD = 56 # Key code constant: Left Alt modifier key. ALT_LEFT = 57 # Key code constant: Right Alt modifier key. ALT_RIGHT = 58 # Key code constant: Left Shift modifier key. SHIFT_LEFT = 59 # Key code constant: Right Shift modifier key. SHIFT_RIGHT = 60 # Key code constant: Tab key. TAB = 61 # Key code constant: Space key. SPACE = 62 # Key code constant: Symbol modifier key. # Used to enter alternate symbols. SYM = 63 # Key code constant: Explorer special function key. # Used to launch a browser application. EXPLORER = 64 # Key code constant: Envelope special function key. # Used to launch a mail application. ENVELOPE = 65 # Key code constant: Enter key. ENTER = 66 # Key code constant: Backspace key. # Deletes characters before the insertion point, unlike {@link #FORWARD_DEL}. DEL = 67 # Key code constant: '`' (backtick) key. GRAVE = 68 # Key code constant: '-'. MINUS = 69 # Key code constant: '=' key. EQUALS = 70 # Key code constant: '[' key. LEFT_BRACKET = 71 # Key code constant: ']' key. RIGHT_BRACKET = 72 # Key code constant: '\' key. BACKSLASH = 73 # Key code constant: ';' key. SEMICOLON = 74 # Key code constant: ''' (apostrophe) key. APOSTROPHE = 75 # Key code constant: '/' key. SLASH = 76 # Key code constant: '@' key. AT = 77 # Key code constant: Number modifier key. # Used to enter numeric symbols. # This key is not Num Lock; it is more like {@link #ALT_LEFT} and is # interpreted as an ALT key NUM = 78 # Key code constant: Headset Hook key. # Used to hang up calls and stop media. HEADSETHOOK = 79 # Key code constant: Camera Focus key. # Used to focus the camera. FOCUS = 80 # *Camera* focus # Key code constant: '+' key. PLUS = 81 # Key code constant: Menu key. MENU = 82 # Key code constant: Notification key. NOTIFICATION = 83 # Key code constant: Search key. SEARCH = 84 # Key code constant: Play/Pause media key. MEDIA_PLAY_PAUSE = 85 # Key code constant: Stop media key. MEDIA_STOP = 86 # Key code constant: Play Next media key. MEDIA_NEXT = 87 # Key code constant: Play Previous media key. MEDIA_PREVIOUS = 88 # Key code constant: Rewind media key. MEDIA_REWIND = 89 # Key code constant: Fast Forward media key. MEDIA_FAST_FORWARD = 90 # Key code constant: Mute key. # Mutes the microphone, unlike {@link #VOLUME_MUTE}. MUTE = 91 # Key code constant: Page Up key. PAGE_UP = 92 # Key code constant: Page Down key. PAGE_DOWN = 93 # Key code constant: Picture Symbols modifier key. # Used to switch symbol sets (Emoji, Kao-moji). PICTSYMBOLS = 94 # switch symbol-sets (Emoji,Kao-moji) # Key code constant: Switch Charset modifier key. # Used to switch character sets (Kanji, Katakana). SWITCH_CHARSET = 95 # switch char-sets (Kanji,Katakana) # Key code constant: A Button key. # On a game controller, the A button should be either the button labeled A # or the first button on the bottom row of controller buttons. BUTTON_A = 96 # Key code constant: B Button key. # On a game controller, the B button should be either the button labeled B # or the second button on the bottom row of controller buttons. BUTTON_B = 97 # Key code constant: C Button key. # On a game controller, the C button should be either the button labeled C # or the third button on the bottom row of controller buttons. BUTTON_C = 98 # Key code constant: X Button key. # On a game controller, the X button should be either the button labeled X # or the first button on the upper row of controller buttons. BUTTON_X = 99 # Key code constant: Y Button key. # On a game controller, the Y button should be either the button labeled Y # or the second button on the upper row of controller buttons. BUTTON_Y = 100 # Key code constant: Z Button key. # On a game controller, the Z button should be either the button labeled Z # or the third button on the upper row of controller buttons. BUTTON_Z = 101 # Key code constant: L1 Button key. # On a game controller, the L1 button should be either the button labeled L1 (or L) # or the top left trigger button. BUTTON_L1 = 102 # Key code constant: R1 Button key. # On a game controller, the R1 button should be either the button labeled R1 (or R) # or the top right trigger button. BUTTON_R1 = 103 # Key code constant: L2 Button key. # On a game controller, the L2 button should be either the button labeled L2 # or the bottom left trigger button. BUTTON_L2 = 104 # Key code constant: R2 Button key. # On a game controller, the R2 button should be either the button labeled R2 # or the bottom right trigger button. BUTTON_R2 = 105 # Key code constant: Left Thumb Button key. # On a game controller, the left thumb button indicates that the left (or only) # joystick is pressed. BUTTON_THUMBL = 106 # Key code constant: Right Thumb Button key. # On a game controller, the right thumb button indicates that the right # joystick is pressed. BUTTON_THUMBR = 107 # Key code constant: Start Button key. # On a game controller, the button labeled Start. BUTTON_START = 108 # Key code constant: Select Button key. # On a game controller, the button labeled Select. BUTTON_SELECT = 109 # Key code constant: Mode Button key. # On a game controller, the button labeled Mode. BUTTON_MODE = 110 # Key code constant: Escape key. ESCAPE = 111 # Key code constant: Forward Delete key. # Deletes characters ahead of the insertion point, unlike {@link #DEL}. FORWARD_DEL = 112 # Key code constant: Left Control modifier key. CTRL_LEFT = 113 # Key code constant: Right Control modifier key. CTRL_RIGHT = 114 # Key code constant: Caps Lock key. CAPS_LOCK = 115 # Key code constant: Scroll Lock key. SCROLL_LOCK = 116 # Key code constant: Left Meta modifier key. META_LEFT = 117 # Key code constant: Right Meta modifier key. META_RIGHT = 118 # Key code constant: Function modifier key. FUNCTION = 119 # Key code constant: System Request / Print Screen key. SYSRQ = 120 # Key code constant: Break / Pause key. BREAK = 121 # Key code constant: Home Movement key. # Used for scrolling or moving the cursor around to the start of a line # or to the top of a list. MOVE_HOME = 122 # Key code constant: End Movement key. # Used for scrolling or moving the cursor around to the end of a line # or to the bottom of a list. MOVE_END = 123 # Key code constant: Insert key. # Toggles insert / overwrite edit mode. INSERT = 124 # Key code constant: Forward key. # Navigates forward in the history stack. Complement of {@link #BACK}. FORWARD = 125 # Key code constant: Play media key. MEDIA_PLAY = 126 # Key code constant: Pause media key. MEDIA_PAUSE = 127 # Key code constant: Close media key. # May be used to close a CD tray, for example. MEDIA_CLOSE = 128 # Key code constant: Eject media key. # May be used to eject a CD tray, for example. MEDIA_EJECT = 129 # Key code constant: Record media key. MEDIA_RECORD = 130 # Key code constant: F1 key. F1 = 131 # Key code constant: F2 key. F2 = 132 # Key code constant: F3 key. F3 = 133 # Key code constant: F4 key. F4 = 134 # Key code constant: F5 key. F5 = 135 # Key code constant: F6 key. F6 = 136 # Key code constant: F7 key. F7 = 137 # Key code constant: F8 key. F8 = 138 # Key code constant: F9 key. F9 = 139 # Key code constant: F10 key. F10 = 140 # Key code constant: F11 key. F11 = 141 # Key code constant: F12 key. F12 = 142 # Key code constant: Num Lock key. # This is the Num Lock key; it is different from {@link #NUM}. # This key alters the behavior of other keys on the numeric keypad. NUM_LOCK = 143 # Key code constant: Numeric keypad '0' key. NUMPAD_0 = 144 # Key code constant: Numeric keypad '1' key. NUMPAD_1 = 145 # Key code constant: Numeric keypad '2' key. NUMPAD_2 = 146 # Key code constant: Numeric keypad '3' key. NUMPAD_3 = 147 # Key code constant: Numeric keypad '4' key. NUMPAD_4 = 148 # Key code constant: Numeric keypad '5' key. NUMPAD_5 = 149 # Key code constant: Numeric keypad '6' key. NUMPAD_6 = 150 # Key code constant: Numeric keypad '7' key. NUMPAD_7 = 151 # Key code constant: Numeric keypad '8' key. NUMPAD_8 = 152 # Key code constant: Numeric keypad '9' key. NUMPAD_9 = 153 # Key code constant: Numeric keypad '/' key (for division). NUMPAD_DIVIDE = 154 # Key code constant: Numeric keypad '#' key (for multiplication). NUMPAD_MULTIPLY = 155 # Key code constant: Numeric keypad '-' key (for subtraction). NUMPAD_SUBTRACT = 156 # Key code constant: Numeric keypad '+' key (for addition). NUMPAD_ADD = 157 # Key code constant: Numeric keypad '.' key (for decimals or digit grouping). NUMPAD_DOT = 158 # Key code constant: Numeric keypad ',' key (for decimals or digit grouping). NUMPAD_COMMA = 159 # Key code constant: Numeric keypad Enter key. NUMPAD_ENTER = 160 # Key code constant: Numeric keypad '=' key. NUMPAD_EQUALS = 161 # Key code constant: Numeric keypad '(' key. NUMPAD_LEFT_PAREN = 162 # Key code constant: Numeric keypad ')' key. NUMPAD_RIGHT_PAREN = 163 # Key code constant: Volume Mute key. # Mutes the speaker, unlike {@link #MUTE}. # This key should normally be implemented as a toggle such that the first press # mutes the speaker and the second press restores the original volume. VOLUME_MUTE = 164 # Key code constant: Info key. # Common on TV remotes to show additional information related to what is # currently being viewed. INFO = 165 # Key code constant: Channel up key. # On TV remotes, increments the television channel. CHANNEL_UP = 166 # Key code constant: Channel down key. # On TV remotes, decrements the television channel. CHANNEL_DOWN = 167 # Key code constant: Zoom in key. KEYCODE_ZOOM_IN = 168 # Key code constant: Zoom out key. KEYCODE_ZOOM_OUT = 169 # Key code constant: TV key. # On TV remotes, switches to viewing live TV. TV = 170 # Key code constant: Window key. # On TV remotes, toggles picture-in-picture mode or other windowing functions. WINDOW = 171 # Key code constant: Guide key. # On TV remotes, shows a programming guide. GUIDE = 172 # Key code constant: DVR key. # On some TV remotes, switches to a DVR mode for recorded shows. DVR = 173 # Key code constant: Bookmark key. # On some TV remotes, bookmarks content or web pages. BOOKMARK = 174 # Key code constant: Toggle captions key. # Switches the mode for closed-captioning text, for example during television shows. CAPTIONS = 175 # Key code constant: Settings key. # Starts the system settings activity. SETTINGS = 176 # Key code constant: TV power key. # On TV remotes, toggles the power on a television screen. TV_POWER = 177 # Key code constant: TV input key. # On TV remotes, switches the input on a television screen. TV_INPUT = 178 # Key code constant: Set-top-box power key. # On TV remotes, toggles the power on an external Set-top-box. STB_POWER = 179 # Key code constant: Set-top-box input key. # On TV remotes, switches the input mode on an external Set-top-box. STB_INPUT = 180 # Key code constant: A/V Receiver power key. # On TV remotes, toggles the power on an external A/V Receiver. AVR_POWER = 181 # Key code constant: A/V Receiver input key. # On TV remotes, switches the input mode on an external A/V Receiver. AVR_INPUT = 182 # Key code constant: Red "programmable" key. # On TV remotes, acts as a contextual/programmable key. PROG_RED = 183 # Key code constant: Green "programmable" key. # On TV remotes, actsas a contextual/programmable key. PROG_GREEN = 184 # Key code constant: Yellow "programmable" key. # On TV remotes, acts as a contextual/programmable key. PROG_YELLOW = 185 # Key code constant: Blue "programmable" key. # On TV remotes, acts as a contextual/programmable key. PROG_BLUE = 186 # Key code constant: App switch key. # Should bring up the application switcher dialog. APP_SWITCH = 187 # Key code constant: Generic Game Pad Button #1. BUTTON_1 = 188 # Key code constant: Generic Game Pad Button #2. BUTTON_2 = 189 # Key code constant: Generic Game Pad Button #3. BUTTON_3 = 190 # Key code constant: Generic Game Pad Button #4. BUTTON_4 = 191 # Key code constant: Generic Game Pad Button #5. BUTTON_5 = 192 # Key code constant: Generic Game Pad Button #6. BUTTON_6 = 193 # Key code constant: Generic Game Pad Button #7. BUTTON_7 = 194 # Key code constant: Generic Game Pad Button #8. BUTTON_8 = 195 # Key code constant: Generic Game Pad Button #9. BUTTON_9 = 196 # Key code constant: Generic Game Pad Button #10. BUTTON_10 = 197 # Key code constant: Generic Game Pad Button #11. BUTTON_11 = 198 # Key code constant: Generic Game Pad Button #12. BUTTON_12 = 199 # Key code constant: Generic Game Pad Button #13. BUTTON_13 = 200 # Key code constant: Generic Game Pad Button #14. BUTTON_14 = 201 # Key code constant: Generic Game Pad Button #15. BUTTON_15 = 202 # Key code constant: Generic Game Pad Button #16. BUTTON_16 = 203 # Key code constant: Language Switch key. # Toggles the current input language such as switching between English and Japanese on # a QWERTY keyboard. On some devices, the same function may be performed by # pressing Shift+Spacebar. LANGUAGE_SWITCH = 204 # Key code constant: Manner Mode key. # Toggles silent or vibrate mode on and off to make the device behave more politely # in certain settings such as on a crowded train. On some devices, the key may only # operate when long-pressed. MANNER_MODE = 205 # Key code constant: 3D Mode key. # Toggles the display between 2D and 3D mode. MODE_3D = 206 # Key code constant: Contacts special function key. # Used to launch an address book application. CONTACTS = 207 # Key code constant: Calendar special function key. # Used to launch a calendar application. CALENDAR = 208 # Key code constant: Music special function key. # Used to launch a music player application. MUSIC = 209 # Key code constant: Calculator special function key. # Used to launch a calculator application. CALCULATOR = 210 # Key code constant: Japanese full-width / half-width key. ZENKAKU_HANKAKU = 211 # Key code constant: Japanese alphanumeric key. EISU = 212 # Key code constant: Japanese non-conversion key. MUHENKAN = 213 # Key code constant: Japanese conversion key. HENKAN = 214 # Key code constant: Japanese katakana / hiragana key. KATAKANA_HIRAGANA = 215 # Key code constant: Japanese Yen key. YEN = 216 # Key code constant: Japanese Ro key. RO = 217 # Key code constant: Japanese kana key. KANA = 218 # Key code constant: Assist key. # Launches the global assist activity. Not delivered to applications. ASSIST = 219 # Key code constant: Brightness Down key. # Adjusts the screen brightness down. BRIGHTNESS_DOWN = 220 # Key code constant: Brightness Up key. # Adjusts the screen brightness up. BRIGHTNESS_UP = 221 # Key code constant: Audio Track key. # Switches the audio tracks. MEDIA_AUDIO_TRACK = 222 # Key code constant: Sleep key. # Puts the device to sleep. Behaves somewhat like {@link #POWER} but it # has no effect if the device is already asleep. SLEEP = 223 # Key code constant: Wakeup key. # Wakes up the device. Behaves somewhat like {@link #POWER} but it # has no effect if the device is already awake. WAKEUP = 224 # Key code constant: Pairing key. # Initiates peripheral pairing mode. Useful for pairing remote control # devices or game controllers, especially if no other input mode is # available. PAIRING = 225 # Key code constant: Media Top Menu key. # Goes to the top of media menu. MEDIA_TOP_MENU = 226 # Key code constant: '11' key. KEY_11 = 227 # Key code constant: '12' key. KEY_12 = 228 # Key code constant: Last Channel key. # Goes to the last viewed channel. LAST_CHANNEL = 229 # Key code constant: TV data service key. # Displays data services like weather, sports. TV_DATA_SERVICE = 230 # Key code constant: Voice Assist key. # Launches the global voice assist activity. Not delivered to applications. VOICE_ASSIST = 231 # Key code constant: Radio key. # Toggles TV service / Radio service. TV_RADIO_SERVICE = 232 # Key code constant: Teletext key. # Displays Teletext service. TV_TELETEXT = 233 # Key code constant: Number entry key. # Initiates to enter multi-digit channel nubmber when each digit key is assigned # for selecting separate channel. Corresponds to Number Entry Mode (0x1D) of CEC # User Control Code. TV_NUMBER_ENTRY = 234 # Key code constant: Analog Terrestrial key. # Switches to analog terrestrial broadcast service. TV_TERRESTRIAL_ANALOG = 235 # Key code constant: Digital Terrestrial key. # Switches to digital terrestrial broadcast service. TV_TERRESTRIAL_DIGITAL = 236 # Key code constant: Satellite key. # Switches to digital satellite broadcast service. TV_SATELLITE = 237 # Key code constant: BS key. # Switches to BS digital satellite broadcasting service available in Japan. TV_SATELLITE_BS = 238 # Key code constant: CS key. # Switches to CS digital satellite broadcasting service available in Japan. TV_SATELLITE_CS = 239 # Key code constant: BS/CS key. # Toggles between BS and CS digital satellite services. TV_SATELLITE_SERVICE = 240 # Key code constant: Toggle Network key. # Toggles selecting broacast services. TV_NETWORK = 241 # Key code constant: Antenna/Cable key. # Toggles broadcast input source between antenna and cable. TV_ANTENNA_CABLE = 242 # Key code constant: HDMI #1 key. # Switches to HDMI input #1. TV_INPUT_HDMI_1 = 243 # Key code constant: HDMI #2 key. # Switches to HDMI input #2. TV_INPUT_HDMI_2 = 244 # Key code constant: HDMI #3 key. # Switches to HDMI input #3. TV_INPUT_HDMI_3 = 245 # Key code constant: HDMI #4 key. # Switches to HDMI input #4. TV_INPUT_HDMI_4 = 246 # Key code constant: Composite #1 key. # Switches to composite video input #1. TV_INPUT_COMPOSITE_1 = 247 # Key code constant: Composite #2 key. # Switches to composite video input #2. TV_INPUT_COMPOSITE_2 = 248 # Key code constant: Component #1 key. # Switches to component video input #1. TV_INPUT_COMPONENT_1 = 249 # Key code constant: Component #2 key. # Switches to component video input #2. TV_INPUT_COMPONENT_2 = 250 # Key code constant: VGA #1 key. # Switches to VGA (analog RGB) input #1. TV_INPUT_VGA_1 = 251 # Key code constant: Audio description key. # Toggles audio description off / on. TV_AUDIO_DESCRIPTION = 252 # Key code constant: Audio description mixing volume up key. # Louden audio description volume as compared with normal audio volume. TV_AUDIO_DESCRIPTION_MIX_UP = 253 # Key code constant: Audio description mixing volume down key. # Lessen audio description volume as compared with normal audio volume. TV_AUDIO_DESCRIPTION_MIX_DOWN = 254 # Key code constant: Zoom mode key. # Changes Zoom mode (Normal, Full, Zoom, Wide-zoom, etc.) TV_ZOOM_MODE = 255 # Key code constant: Contents menu key. # Goes to the title list. Corresponds to Contents Menu (0x0B) of CEC User Control # Code TV_CONTENTS_MENU = 256 # Key code constant: Media context menu key. # Goes to the context menu of media contents. Corresponds to Media Context-sensitive # Menu (0x11) of CEC User Control Code. TV_MEDIA_CONTEXT_MENU = 257 # Key code constant: Timer programming key. # Goes to the timer recording menu. Corresponds to Timer Programming (0x54) of # CEC User Control Code. TV_TIMER_PROGRAMMING = 258 # Key code constant: Help key. HELP = 259 # Key code constant: Navigate to previous key. # Goes backward by one item in an ordered collection of items. NAVIGATE_PREVIOUS = 260 # Key code constant: Navigate to next key. # Advances to the next item in an ordered collection of items. NAVIGATE_NEXT = 261 # Key code constant: Navigate in key. # Activates the item that currently has focus or expands to the next level of a navigation # hierarchy. NAVIGATE_IN = 262 # Key code constant: Navigate out key. # Backs out one level of a navigation hierarchy or collapses the item that currently has # focus. NAVIGATE_OUT = 263 # Key code constant: Primary stem key for Wear. # Main power/reset button on watch. STEM_PRIMARY = 264 # Key code constant: Generic stem key 1 for Wear. STEM_1 = 265 # Key code constant: Generic stem key 2 for Wear. STEM_2 = 266 # Key code constant: Generic stem key 3 for Wear. STEM_3 = 267 # Key code constant: Directional Pad Up-Left. DPAD_UP_LEFT = 268 # Key code constant: Directional Pad Down-Left. DPAD_DOWN_LEFT = 269 # Key code constant: Directional Pad Up-Right. DPAD_UP_RIGHT = 270 # Key code constant: Directional Pad Down-Right. DPAD_DOWN_RIGHT = 271 # Key code constant: Skip forward media key. MEDIA_SKIP_FORWARD = 272 # Key code constant: Skip backward media key. MEDIA_SKIP_BACKWARD = 273 # Key code constant: Step forward media key. # Steps media forward, one frame at a time. MEDIA_STEP_FORWARD = 274 # Key code constant: Step backward media key. # Steps media backward, one frame at a time. MEDIA_STEP_BACKWARD = 275 # Key code constant: put device to sleep unless a wakelock is held. SOFT_SLEEP = 276 # Key code constant: Cut key. CUT = 277 # Key code constant: Copy key. COPY = 278 gamepad_buttons = [ BUTTON_A, BUTTON_B, BUTTON_C, BUTTON_X, BUTTON_Y, BUTTON_Z, BUTTON_L1, BUTTON_R1, BUTTON_L2, BUTTON_R2, BUTTON_THUMBL, BUTTON_THUMBR, BUTTON_START, BUTTON_SELECT, BUTTON_MODE, BUTTON_1, BUTTON_2, BUTTON_3, BUTTON_4, BUTTON_5, BUTTON_6, BUTTON_7, BUTTON_8, BUTTON_9, BUTTON_10, BUTTON_11, BUTTON_12, BUTTON_13, BUTTON_14, BUTTON_15, BUTTON_16, ] @staticmethod def is_gamepad_button(code: int) -> bool: """Returns true if the specified nativekey is a gamepad button.""" return code in AndroidKey.gamepad_buttons confirm_buttons = [DPAD_CENTER, ENTER, SPACE, NUMPAD_ENTER] @staticmethod def is_confirm_key(code: int) -> bool: """Returns true if the key will, by default, trigger a click on the focused view.""" return code in AndroidKey.confirm_buttons media_buttons = [ MEDIA_PLAY, MEDIA_PAUSE, MEDIA_PLAY_PAUSE, MUTE, HEADSETHOOK, MEDIA_STOP, MEDIA_NEXT, MEDIA_PREVIOUS, MEDIA_REWIND, MEDIA_RECORD, MEDIA_FAST_FORWARD, ] @staticmethod def is_media_key(code: int) -> bool: """Returns true if this key is a media key, which can be send to apps that are interested in media key events.""" return code in AndroidKey.media_buttons system_buttons = [ MENU, SOFT_RIGHT, HOME, BACK, CALL, ENDCALL, VOLUME_UP, VOLUME_DOWN, VOLUME_MUTE, MUTE, POWER, HEADSETHOOK, MEDIA_PLAY, MEDIA_PAUSE, MEDIA_PLAY_PAUSE, MEDIA_STOP, MEDIA_NEXT, MEDIA_PREVIOUS, MEDIA_REWIND, MEDIA_RECORD, MEDIA_FAST_FORWARD, CAMERA, FOCUS, SEARCH, BRIGHTNESS_DOWN, BRIGHTNESS_UP, MEDIA_AUDIO_TRACK, ] @staticmethod def is_system_key(code: int) -> bool: """Returns true if the key is a system key, System keys can not be used for menu shortcuts.""" return code in AndroidKey.system_buttons wake_buttons = [BACK, MENU, WAKEUP, PAIRING, STEM_1, STEM_2, STEM_3] @staticmethod def is_wake_key(code: int) -> bool: """Returns true if the key is a wake key.""" return code in AndroidKey.wake_buttons
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/android/nativekey.py
nativekey.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, cast from selenium.common.exceptions import UnknownMethodException from appium.common.helper import extract_const_attributes from appium.common.logger import logger from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from appium.webdriver.mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class GsmCallActions: CALL = 'call' ACCEPT = 'accept' CANCEL = 'cancel' HOLD = 'hold' class GsmSignalStrength: NONE_OR_UNKNOWN = 0 POOR = 1 MODERATE = 2 GOOD = 3 GREAT = 4 class GsmVoiceState: UNREGISTERED = 'unregistered' HOME = 'home' ROAMING = 'roaming' SEARCHING = 'searching' DENIED = 'denied' OFF = 'off' ON = 'on' class Gsm(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): def make_gsm_call(self, phone_number: str, action: str) -> 'WebDriver': """Make GSM call (Emulator only) Android only. Args: phone_number: The phone number to call to. action: The call action. A member of the const `appium.webdriver.extensions.android.gsm.GsmCallActions` Usage: self.driver.make_gsm_call('5551234567', GsmCallActions.CALL) Returns: Union['WebDriver', 'Gsm']: Self instance """ ext_name = 'mobile: gsmCall' constants = extract_const_attributes(GsmCallActions) if action not in constants.values(): logger.warning( f'{action} is unknown. Consider using one of {list(constants.keys())} constants. ' f'(e.g. {GsmCallActions.__name__}.CALL)' ) args = {'phoneNumber': phone_number, 'action': action} try: self.assert_extension_exists(ext_name).execute_script(ext_name, args) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.MAKE_GSM_CALL, args) return cast('WebDriver', self) def set_gsm_signal(self, strength: int) -> 'WebDriver': """Set GSM signal strength (Emulator only) Android only. Args: strength: Signal strength. A member of the enum :obj:`appium.webdriver.extensions.android.gsm.GsmSignalStrength` Usage: self.driver.set_gsm_signal(GsmSignalStrength.GOOD) Returns: Union['WebDriver', 'Gsm']: Self instance """ ext_name = 'mobile: gsmSignal' constants = extract_const_attributes(GsmSignalStrength) if strength not in constants.values(): logger.warning( f'{strength} is out of range. Consider using one of {list(constants.keys())} constants. ' f'(e.g. {GsmSignalStrength.__name__}.GOOD)' ) try: self.assert_extension_exists(ext_name).execute_script(ext_name, {'strength': strength}) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute( Command.SET_GSM_SIGNAL, {'signalStrength': strength, 'signalStrengh': strength} ) return cast('WebDriver', self) def set_gsm_voice(self, state: str) -> 'WebDriver': """Set GSM voice state (Emulator only) Android only. Args: state: State of GSM voice. A member of the const `appium.webdriver.extensions.android.gsm.GsmVoiceState` Usage: self.driver.set_gsm_voice(GsmVoiceState.HOME) Returns: Union['WebDriver', 'Gsm']: Self instance """ ext_name = 'mobile: gmsVoice' constants = extract_const_attributes(GsmVoiceState) if state not in constants.values(): logger.warning( f'{state} is unknown. Consider using one of {list(constants.keys())} constants. ' f'(e.g. {GsmVoiceState.__name__}.HOME)' ) args = {'state': state} try: self.assert_extension_exists(ext_name).execute_script(ext_name, args) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.SET_GSM_VOICE, args) return cast('WebDriver', self) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.MAKE_GSM_CALL] = ('POST', '/session/$sessionId/appium/device/gsm_call') commands[Command.SET_GSM_SIGNAL] = ( 'POST', '/session/$sessionId/appium/device/gsm_signal', ) commands[Command.SET_GSM_VOICE] = ('POST', '/session/$sessionId/appium/device/gsm_voice')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/android/gsm.py
gsm.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Dict, List, Union from selenium.common.exceptions import UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from appium.webdriver.mobilecommand import MobileCommand as Command class Performance(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): def get_performance_data( self, package_name: str, data_type: str, data_read_timeout: Union[int, None] = None ) -> List[List[str]]: """Returns the information of the system state which is supported to read as like cpu, memory, network traffic, and battery. Android only. Args: package_name: The package name of the application data_type: The type of system state which wants to read. It should be one of the supported performance data types. Check :func:`.get_performance_data_types` for supported types data_read_timeout: The number of attempts to read Usage: self.driver.get_performance_data('my.app.package', 'cpuinfo', 5) Returns: The data along to `data_type` """ ext_name = 'mobile: getPerformanceData' args: Dict[str, Union[str, int]] = {'packageName': package_name, 'dataType': data_type} try: return self.assert_extension_exists(ext_name).execute_script(ext_name, args) except UnknownMethodException: # TODO: Remove the fallback if data_read_timeout is not None: args['dataReadTimeout'] = data_read_timeout return self.mark_extension_absence(ext_name).execute(Command.GET_PERFORMANCE_DATA, args)['value'] def get_performance_data_types(self) -> List[str]: """Returns the information types of the system state which is supported to read as like cpu, memory, network traffic, and battery. Android only. Usage: self.driver.get_performance_data_types() Returns: Available data types """ ext_name = 'mobile: getPerformanceDataTypes' try: return self.assert_extension_exists(ext_name).execute_script(ext_name) except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute(Command.GET_PERFORMANCE_DATA_TYPES)['value'] def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.GET_PERFORMANCE_DATA] = ( 'POST', '/session/$sessionId/appium/getPerformanceData', ) commands[Command.GET_PERFORMANCE_DATA_TYPES] = ( 'POST', '/session/$sessionId/appium/performanceData/types', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/android/performance.py
performance.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, cast from selenium.common.exceptions import UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from appium.webdriver.mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class Sms(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): def send_sms(self, phone_number: str, message: str) -> 'WebDriver': """Emulate send SMS event on the connected emulator. Android only. Args: phone_number: The phone number of message sender message: The message to send Usage: self.driver.send_sms('555-123-4567', 'Hey lol') Returns: Union['WebDriver', 'Sms']: Self instance """ ext_name = 'mobile: sendSms' args = {'phoneNumber': phone_number, 'message': message} try: self.assert_extension_exists(ext_name).execute_script(ext_name, args) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.SEND_SMS, args) return cast('WebDriver', self) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.SEND_SMS] = ('POST', '/session/$sessionId/appium/device/send_sms')
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/android/sms.py
sms.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING, cast from selenium.common.exceptions import UnknownMethodException from appium.common.helper import extract_const_attributes from appium.common.logger import logger from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from appium.webdriver.mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class NetSpeed: GSM = 'gsm' # GSM/CSD (up: 14.4(kbps), down: 14.4(kbps)) SCSD = 'scsd' # HSCSD (up: 14.4, down: 57.6) GPRS = 'gprs' # GPRS (up: 28.8, down: 57.6) EDGE = 'edge' # EDGE/EGPRS (up: 473.6, down: 473.6) UMTS = 'umts' # UMTS/3G (up: 384.0, down: 384.0) HSDPA = 'hsdpa' # HSDPA (up: 5760.0, down: 13,980.0) LTE = 'lte' # LTE (up: 58,000, down: 173,000) EVDO = 'evdo' # EVDO (up: 75,000, down: 280,000) FULL = 'full' # No limit, the default (up: 0.0, down: 0.0) class NetworkMask: WIFI = 0b010 DATA = 0b100 AIRPLANE_MODE = 0b001 class Network(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): @property def network_connection(self) -> int: """Returns an integer bitmask specifying the network connection type. Android only. Possible values are available through the enumeration `appium.webdriver.ConnectionType` This API only works reliably on emulators (any version) and real devices since API level 31. """ ext_name = 'mobile: getConnectivity' try: result_map = self.assert_extension_exists(ext_name).execute_script(ext_name) return ( (NetworkMask.WIFI if result_map['wifi'] else 0) | (NetworkMask.DATA if result_map['data'] else 0) | (NetworkMask.AIRPLANE_MODE if result_map['airplaneMode'] else 0) ) except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute(Command.GET_NETWORK_CONNECTION, {})['value'] def set_network_connection(self, connection_type: int) -> int: """Sets the network connection type. Android only. Possible values: +--------------------+------+------+---------------+ | Value (Alias) | Data | Wifi | Airplane Mode | +====================+======+======+===============+ | 0 (None) | 0 | 0 | 0 | +--------------------+------+------+---------------+ | 1 (Airplane Mode) | 0 | 0 | 1 | +--------------------+------+------+---------------+ | 2 (Wifi only) | 0 | 1 | 0 | +--------------------+------+------+---------------+ | 4 (Data only) | 1 | 0 | 0 | +--------------------+------+------+---------------+ | 6 (All network on) | 1 | 1 | 0 | +--------------------+------+------+---------------+ These are available through the enumeration `appium.webdriver.ConnectionType` This API only works reliably on emulators (any version) and real devices since API level 31. Args: connection_type: a member of the enum `appium.webdriver.ConnectionType` Return: int: Set network connection type """ ext_name = 'mobile: setConnectivity' try: return self.assert_extension_exists(ext_name).execute_script( ext_name, { 'wifi': bool(connection_type & NetworkMask.WIFI), 'data': bool(connection_type & NetworkMask.DATA), 'airplaneMode': bool(connection_type & NetworkMask.AIRPLANE_MODE), }, ) except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute( Command.SET_NETWORK_CONNECTION, {'parameters': {'type': connection_type}} )['value'] def toggle_wifi(self) -> 'WebDriver': """Toggle the wifi on the device, Android only. This API only works reliably on emulators (any version) and real devices since API level 31. Returns: Union['WebDriver', 'Network']: Self instance """ ext_name = 'mobile: setConnectivity' try: self.assert_extension_exists(ext_name).execute_script( ext_name, {'wifi': not (self.network_connection & NetworkMask.WIFI)} ) except UnknownMethodException: self.mark_extension_absence(ext_name).execute(Command.TOGGLE_WIFI, {}) return cast('WebDriver', self) def set_network_speed(self, speed_type: str) -> 'WebDriver': """Set the network speed emulation. Android Emulator only. Args: speed_type: The network speed type. A member of the const appium.webdriver.extensions.android.network.NetSpeed. Usage: self.driver.set_network_speed(NetSpeed.LTE) Returns: Union['WebDriver', 'Network']: Self instance """ constants = extract_const_attributes(NetSpeed) if speed_type not in constants.values(): logger.warning( f'{speed_type} is unknown. Consider using one of {list(constants.keys())} constants. ' f'(e.g. {NetSpeed.__name__}.LTE)' ) ext_name = 'mobile: networkSpeed' try: self.assert_extension_exists(ext_name).execute_script(ext_name, {'speed': speed_type}) except UnknownMethodException: # TODO: Remove the fallback self.mark_extension_absence(ext_name).execute(Command.SET_NETWORK_SPEED, {'netspeed': speed_type}) return cast('WebDriver', self) def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.TOGGLE_WIFI] = ('POST', '/session/$sessionId/appium/device/toggle_wifi') commands[Command.GET_NETWORK_CONNECTION] = ( 'GET', '/session/$sessionId/network_connection', ) commands[Command.SET_NETWORK_CONNECTION] = ( 'POST', '/session/$sessionId/network_connection', ) commands[Command.SET_NETWORK_SPEED] = ( 'POST', '/session/$sessionId/appium/device/network_speed', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/android/network.py
network.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Dict, Union from selenium.common.exceptions import UnknownMethodException from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from appium.webdriver.mobilecommand import MobileCommand as Command class SystemBars(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): def get_system_bars(self) -> Dict[str, Dict[str, Union[int, bool]]]: """Retrieve visibility and bounds information of the status and navigation bars. Android only. Returns: A dictionary whose keys are - statusBar - visible - x - y - width - height - navigationBar - visible - x - y - width - height """ ext_name = 'mobile: getSystemBars' try: return self.assert_extension_exists(ext_name).execute_script(ext_name) except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute(Command.GET_SYSTEM_BARS)['value'] def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.GET_SYSTEM_BARS] = ( 'GET', '/session/$sessionId/appium/device/system_bars', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/android/system_bars.py
system_bars.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import TYPE_CHECKING, cast from selenium.common.exceptions import TimeoutException, UnknownMethodException from selenium.webdriver.support.ui import WebDriverWait from appium.protocols.webdriver.can_execute_commands import CanExecuteCommands from appium.protocols.webdriver.can_execute_scripts import CanExecuteScripts from appium.protocols.webdriver.can_remember_extension_presence import CanRememberExtensionPresence from appium.webdriver.mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver class Activities(CanExecuteCommands, CanExecuteScripts, CanRememberExtensionPresence): def start_activity(self, app_package: str, app_activity: str, **opts: str) -> 'WebDriver': """Opens an arbitrary activity during a test. If the activity belongs to another application, that application is started and the activity is opened. deprecated:: 2.9.0 This is an Android-only method. Args: app_package: The package containing the activity to start. app_activity: The activity to start. Keyword Args: app_wait_package (str): Begin automation after this package starts. app_wait_activity (str): Begin automation after this activity starts. intent_action (str): Intent to start. intent_category (str): Intent category to start. intent_flags (str): Flags to send to the intent. optional_intent_arguments (str): Optional arguments to the intent. dont_stop_app_on_reset (str): Should the app be stopped on reset? """ warnings.warn( 'The "session" API is deprecated. Use "mobile: startActivity" extension instead.', DeprecationWarning, ) data = {'appPackage': app_package, 'appActivity': app_activity} arguments = { 'app_wait_package': 'appWaitPackage', 'app_wait_activity': 'appWaitActivity', 'intent_action': 'intentAction', 'intent_category': 'intentCategory', 'intent_flags': 'intentFlags', 'optional_intent_arguments': 'optionalIntentArguments', 'dont_stop_app_on_reset': 'dontStopAppOnReset', } for key, value in arguments.items(): if key in opts: data[value] = opts[key] self.execute(Command.START_ACTIVITY, data) return cast('WebDriver', self) @property def current_activity(self) -> str: """Retrieves the current activity running on the device. Returns: str: The current activity name running on the device """ ext_name = 'mobile: getCurrentActivity' try: return self.assert_extension_exists(ext_name).execute_script(ext_name) except UnknownMethodException: # TODO: Remove the fallback return self.mark_extension_absence(ext_name).execute(Command.GET_CURRENT_ACTIVITY)['value'] def wait_activity(self, activity: str, timeout: int, interval: int = 1) -> bool: """Wait for an activity: block until target activity presents or time out. This is an Android-only method. Args: activity: target activity timeout: max wait time, in seconds interval: sleep interval between retries, in seconds Returns: `True` if the target activity is shown """ try: WebDriverWait(self, timeout, interval).until(lambda d: d.current_activity == activity) return True except TimeoutException: return False def _add_commands(self) -> None: # noinspection PyProtectedMember,PyUnresolvedReferences commands = self.command_executor._commands commands[Command.GET_CURRENT_ACTIVITY] = ( 'GET', '/session/$sessionId/appium/device/current_activity', ) commands[Command.START_ACTIVITY] = ( 'POST', '/session/$sessionId/appium/device/start_activity', )
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/extensions/android/activities.py
activities.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # The Selenium team implemented something like the Multi Action API in the form of # "action chains" (https://code.google.com/p/selenium/source/browse/py/selenium/webdriver/common/action_chains.py). # These do not quite work for this situation, and do not allow for ad hoc action # chaining as the spec requires. import copy import warnings from typing import TYPE_CHECKING, Dict, List, Optional, Union from appium.webdriver.mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.common.touch_action import TouchAction from appium.webdriver.webdriver import WebDriver from appium.webdriver.webelement import WebElement class MultiAction: """ deprecated:: 2.0.0 Please use W3C actions instead: http://appium.io/docs/en/commands/interactions/actions/ """ def __init__(self, driver: 'WebDriver', element: Optional['WebElement'] = None) -> None: warnings.warn( "[Deprecated] 'MultiAction' action is deprecated. Please use W3C actions instead.", DeprecationWarning ) self._driver = driver self._element = element self._touch_actions: List['TouchAction'] = [] def add(self, *touch_actions: 'TouchAction') -> None: """Add TouchAction objects to the MultiAction, to be performed later. Args: touch_actions: one or more TouchAction objects describing a chain of actions to be performed by one finger Usage: | a1 = TouchAction(driver) | a1.press(el1).move_to(el2).release() | a2 = TouchAction(driver) | a2.press(el2).move_to(el1).release() | MultiAction(driver).add(a1, a2) Returns: `MultiAction`: Self instance """ for touch_action in touch_actions: if self._touch_actions is None: self._touch_actions = [] self._touch_actions.append(copy.copy(touch_action)) def perform(self) -> 'MultiAction': """Perform the actions stored in the object. Usage: | a1 = TouchAction(driver) | a1.press(el1).move_to(el2).release() | a2 = TouchAction(driver) | a2.press(el2).move_to(el1).release() | MultiAction(driver).add(a1, a2).perform() Returns: `MultiAction`: Self instance """ self._driver.execute(Command.MULTI_ACTION, self.json_wire_gestures) # clean up and be ready for the next batch self._touch_actions = [] return self @property def json_wire_gestures(self) -> Dict[str, Union[List, str]]: actions = [] for action in self._touch_actions: actions.append(action.json_wire_gestures) if self._element is not None: return {'actions': actions, 'elementId': self._element.id} return {'actions': actions}
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/common/multi_action.py
multi_action.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # The Selenium team implemented a version of the Touch Action API in their code # (https://code.google.com/p/selenium/source/browse/py/selenium/webdriver/common/touch_actions.py) # but it is deficient in many ways, and does not work in such a way as to be # amenable to Appium's use of iOS UIAutomation and Android UIAutomator # So it is reimplemented here. # # Theirs is `TouchActions`. Appium's is `TouchAction`. # pylint: disable=no-self-use import copy import warnings from typing import TYPE_CHECKING, Dict, List, Optional, Union from appium.webdriver.mobilecommand import MobileCommand as Command if TYPE_CHECKING: from appium.webdriver.webdriver import WebDriver from appium.webdriver.webelement import WebElement class TouchAction: """ deprecated:: 2.0.0 Please use W3C actions instead: http://appium.io/docs/en/commands/interactions/actions/ """ def __init__(self, driver: Optional['WebDriver'] = None): warnings.warn( "[Deprecated] 'TouchAction' action is deprecated. Please use W3C actions instead.", DeprecationWarning ) self._driver = driver self._actions: List = [] def tap( self, element: Optional['WebElement'] = None, x: Optional[int] = None, y: Optional[int] = None, count: int = 1, ) -> 'TouchAction': """Perform a tap action on the element Args: element: the element to tap x : x coordinate to tap, relative to the top left corner of the element. y : y coordinate. If y is used, x must also be set, and vice versa Returns: `TouchAction`: Self instance """ opts = self._get_opts(element, x, y) opts['count'] = count self._add_action('tap', opts) return self def press( self, el: Optional['WebElement'] = None, x: Optional[int] = None, y: Optional[int] = None, pressure: Optional[float] = None, ) -> 'TouchAction': """Begin a chain with a press down action at a particular element or point Args: el: the element to press x: x coordiate to press. If y is used, x must also be set y: y coordiate to press. If x is used, y must also be set pressure: [iOS Only] press as force touch. Read the description of `force` property on Apple's UITouch class (https://developer.apple.com/documentation/uikit/uitouch?language=objc) for more details on possible value ranges. Returns: `TouchAction`: Self instance """ self._add_action('press', self._get_opts(el, x, y, pressure=pressure)) return self def long_press( self, el: Optional['WebElement'] = None, x: Optional[int] = None, y: Optional[int] = None, duration: int = 1000, ) -> 'TouchAction': """Begin a chain with a press down that lasts `duration` milliseconds Args: el: the element to press x: x coordiate to press. If y is used, x must also be set y: y coordiate to press. If x is used, y must also be set duration: Duration to press, expressed in milliseconds Returns: `TouchAction`: Self instance """ self._add_action('longPress', self._get_opts(el, x, y, duration)) return self def wait(self, ms: int = 0) -> 'TouchAction': """Pause for `ms` milliseconds. Args: ms: The time to pause Returns: `TouchAction`: Self instance """ if ms is None: ms = 0 opts = {'ms': ms} self._add_action('wait', opts) return self def move_to( self, el: Optional['WebElement'] = None, x: Optional[int] = None, y: Optional[int] = None ) -> 'TouchAction': """Move the pointer from the previous point to the element or point specified Args: el: the element to be moved to x: x coordiate to be moved to. If y is used, x must also be set y: y coordiate to be moved to. If x is used, y must also be set Returns: `TouchAction`: Self instance """ self._add_action('moveTo', self._get_opts(el, x, y)) return self def release(self) -> 'TouchAction': """End the action by lifting the pointer off the screen Returns: `TouchAction`: Self instance """ self._add_action('release', {}) return self def perform(self) -> 'TouchAction': """Perform the action by sending the commands to the server to be operated upon Returns: `TouchAction`: Self instance """ if self._driver is None: raise ValueError('Set driver to constructor as a argument when to create the instance.') params = {'actions': self._actions} self._driver.execute(Command.TOUCH_ACTION, params) # get rid of actions so the object can be reused self._actions = [] return self @property def json_wire_gestures(self) -> List[Dict]: gestures = [] for action in self._actions: gestures.append(copy.deepcopy(action)) return gestures def _add_action(self, action: str, options: Dict) -> None: gesture = { 'action': action, 'options': options, } self._actions.append(gesture) def _get_opts( self, el: Optional['WebElement'] = None, x: Optional[int] = None, y: Optional[int] = None, duration: Optional[int] = None, pressure: Optional[float] = None, ) -> Dict[str, Union[int, float]]: opts = {} if el is not None: opts['element'] = el.id # it makes no sense to have x but no y, or vice versa. if x is not None and y is not None: opts['x'] = x opts['y'] = y if duration is not None: opts['duration'] = duration if pressure is not None: opts['pressure'] = pressure return opts
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/webdriver/common/touch_action.py
touch_action.py
from typing import Dict from appium.options.common.app_option import AppOption from appium.options.common.automation_name_option import AUTOMATION_NAME from appium.options.common.base import PLATFORM_NAME, AppiumOptions from appium.options.common.postrun_option import PostrunOption from appium.options.common.prerun_option import PrerunOption from appium.options.common.system_port_option import SystemPortOption from .app_arguments_option import AppArgumentsOption from .app_top_level_window_option import AppTopLevelWindowOption from .app_working_dir_option import AppWorkingDirOption from .create_session_timeout_option import CreateSessionTimeoutOption from .expreimental_web_driver_option import ExperimentalWebDriverOption from .wait_for_app_launch_option import WaitForAppLaunchOption class WindowsOptions( AppiumOptions, PrerunOption, PostrunOption, AppOption, AppTopLevelWindowOption, AppWorkingDirOption, CreateSessionTimeoutOption, ExperimentalWebDriverOption, SystemPortOption, WaitForAppLaunchOption, AppArgumentsOption, ): @AppOption.app.setter # type: ignore def app(self, value: str) -> None: """ The name of the UWP application to test or full path to a classic app, for example Microsoft.WindowsCalculator_8wekyb3d8bbwe!App or C:\\Windows\\System32\\notepad.exe. It is also possible to set app to Root. In such case the session will be invoked without any explicit target application (actually, it will be Explorer). Either this capability or appTopLevelWindow must be provided on session startup. """ AppOption.app.fset(self, value) # type: ignore @PrerunOption.prerun.setter # type: ignore def prerun(self, value: Dict[str, str]) -> None: """ A mapping containing either 'script' or 'command' key. The value of each key must be a valid PowerShell script or command to be executed prior to the WinAppDriver session startup. See https://github.com/appium/appium-windows-driver#power-shell-commands-execution for more details. """ PrerunOption.prerun.fset(self, value) # type: ignore @PostrunOption.postrun.setter # type: ignore def postrun(self, value: Dict[str, str]) -> None: """ A mapping containing either 'script' or 'command' key. The value of each key must be a valid PowerShell script or command to be executed after a WinAppDriver session is finished. See https://github.com/appium/appium-windows-driver#power-shell-commands-execution for more details. """ PostrunOption.postrun.fset(self, value) # type: ignore @SystemPortOption.system_port.setter # type: ignore def system_port(self, value: int) -> None: """ The port number to execute Appium Windows Driver server listener on, for example 5556. The port must not be occupied. The default starting port number for a new Appium Windows Driver session is 4724. If this port is already busy then the next free port will be automatically selected. """ SystemPortOption.system_port.fset(self, value) # type: ignore @property def default_capabilities(self) -> Dict: return { AUTOMATION_NAME: 'Windows', PLATFORM_NAME: 'Windows', }
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/options/windows/windows/base.py
base.py
from typing import Dict from appium.options.android.common.adb.adb_exec_timeout_option import AdbExecTimeoutOption from appium.options.android.common.adb.adb_port_option import AdbPortOption from appium.options.android.common.adb.allow_delay_adb_option import AllowDelayAdbOption from appium.options.android.common.adb.build_tools_version_option import BuildToolsVersionOption from appium.options.android.common.adb.clear_device_logs_on_start_option import ClearDeviceLogsOnStartOption from appium.options.android.common.adb.ignore_hidden_api_policy_error_option import IgnoreHiddenApiPolicyErrorOption from appium.options.android.common.adb.logcat_filter_specs_option import LogcatFilterSpecsOption from appium.options.android.common.adb.logcat_format_option import LogcatFormatOption from appium.options.android.common.adb.mock_location_app_option import MockLocationAppOption from appium.options.android.common.adb.remote_adb_host_option import RemoteAdbHostOption from appium.options.android.common.adb.skip_logcat_capture_option import SkipLogcatCaptureOption from appium.options.android.common.adb.suppress_kill_server_option import SuppressKillServerOption from appium.options.android.common.app.allow_test_packages_option import AllowTestPackagesOption from appium.options.android.common.app.android_install_timeout_option import AndroidInstallTimeoutOption from appium.options.android.common.app.app_activity_option import AppActivityOption from appium.options.android.common.app.app_package_option import AppPackageOption from appium.options.android.common.app.app_wait_activity_option import AppWaitActivityOption from appium.options.android.common.app.app_wait_duration_option import AppWaitDurationOption from appium.options.android.common.app.app_wait_for_launch_option import AppWaitForLaunchOption from appium.options.android.common.app.app_wait_package_option import AppWaitPackageOption from appium.options.android.common.app.auto_grant_premissions_option import AutoGrantPermissionsOption from appium.options.android.common.app.enforce_app_install_option import EnforceAppInstallOption from appium.options.android.common.app.intent_action_option import IntentActionOption from appium.options.android.common.app.intent_category_option import IntentCategoryOption from appium.options.android.common.app.intent_flags_option import IntentFlagsOption from appium.options.android.common.app.optional_intent_arguments_option import OptionalIntentArgumentsOption from appium.options.android.common.app.remote_apps_cache_limit_option import RemoteAppsCacheLimitOption from appium.options.android.common.app.uninstall_other_packages_option import UninstallOtherPackagesOption from appium.options.android.common.avd.avd_args_option import AvdArgsOption from appium.options.android.common.avd.avd_env_option import AvdEnvOption from appium.options.android.common.avd.avd_launch_timeout_option import AvdLaunchTimeoutOption from appium.options.android.common.avd.avd_option import AvdOption from appium.options.android.common.avd.avd_ready_timeout_option import AvdReadyTimeoutOption from appium.options.android.common.avd.gps_enabled_option import GpsEnabledOption from appium.options.android.common.avd.network_speed_option import NetworkSpeedOption from appium.options.android.common.context.auto_webview_timeout_option import AutoWebviewTimeoutOption from appium.options.android.common.context.chrome_logging_prefs_option import ChromeLoggingPrefsOption from appium.options.android.common.context.chrome_options_option import ChromeOptionsOption from appium.options.android.common.context.chromedriver_args_option import ChromedriverArgsOption from appium.options.android.common.context.chromedriver_chrome_mapping_file_option import ( ChromedriverChromeMappingFileOption, ) from appium.options.android.common.context.chromedriver_disable_build_check_option import ( ChromedriverDisableBuildCheckOption, ) from appium.options.android.common.context.chromedriver_executable_dir_option import ChromedriverExecutableDirOption from appium.options.android.common.context.chromedriver_executable_option import ChromedriverExecutableOption from appium.options.android.common.context.chromedriver_port_option import ChromedriverPortOption from appium.options.android.common.context.chromedriver_ports_option import ChromedriverPortsOption from appium.options.android.common.context.chromedriver_use_system_executable_option import ( ChromedriverUseSystemExecutableOption, ) from appium.options.android.common.context.ensure_webviews_have_pages_option import EnsureWebviewsHavePagesOption from appium.options.android.common.context.extract_chrome_android_package_from_context_name_option import ( ExtractChromeAndroidPackageFromContextNameOption, ) from appium.options.android.common.context.native_web_screenshot_option import NativeWebScreenshotOption from appium.options.android.common.context.recreate_chrome_driver_sessions_option import ( RecreateChromeDriverSessionsOption, ) from appium.options.android.common.context.show_chromedriver_log_option import ShowChromedriverLogOption from appium.options.android.common.context.webview_devtools_port_option import WebviewDevtoolsPortOption from appium.options.android.common.localization.locale_script_option import LocaleScriptOption from appium.options.android.common.locking.skip_unlock_option import SkipUnlockOption from appium.options.android.common.locking.unlock_key_option import UnlockKeyOption from appium.options.android.common.locking.unlock_strategy_option import UnlockStrategyOption from appium.options.android.common.locking.unlock_success_timeout_option import UnlockSuccessTimeoutOption from appium.options.android.common.locking.unlock_type_option import UnlockTypeOption from appium.options.android.common.mjpeg.mjpeg_screenshot_url_option import MjpegScreenshotUrlOption from appium.options.android.common.other.disable_suppress_accessibility_service_option import ( DisableSuppressAccessibilityServiceOption, ) from appium.options.android.common.other.user_profile_option import UserProfileOption from appium.options.android.common.signing.key_alias_option import KeyAliasOption from appium.options.android.common.signing.key_password_option import KeyPasswordOption from appium.options.android.common.signing.keystore_password_option import KeystorePasswordOption from appium.options.android.common.signing.keystore_path_option import KeystorePathOption from appium.options.android.common.signing.no_sign_option import NoSignOption from appium.options.android.common.signing.use_keystore_option import UseKeystoreOption from appium.options.common.app_option import AppOption from appium.options.common.auto_web_view_option import AutoWebViewOption from appium.options.common.automation_name_option import AUTOMATION_NAME from appium.options.common.base import PLATFORM_NAME, AppiumOptions from appium.options.common.clear_system_files_option import ClearSystemFilesOption from appium.options.common.device_name_option import DeviceNameOption from appium.options.common.enable_performance_logging_option import EnablePerformanceLoggingOption from appium.options.common.is_headless_option import IsHeadlessOption from appium.options.common.language_option import LanguageOption from appium.options.common.locale_option import LocaleOption from appium.options.common.orientation_option import OrientationOption from appium.options.common.other_apps_option import OtherAppsOption from appium.options.common.skip_log_capture_option import SkipLogCaptureOption from appium.options.common.system_port_option import SystemPortOption from appium.options.common.udid_option import UdidOption from .disable_window_animation_option import DisableWindowAnimationOption from .mjpeg_server_port_option import MjpegServerPortOption from .skip_device_initialization_option import SkipDeviceInitializationOption from .skip_server_installation_option import SkipServerInstallationOption from .uiautomator2_server_install_timeout_option import Uiautomator2ServerInstallTimeoutOption from .uiautomator2_server_launch_timeout_option import Uiautomator2ServerLaunchTimeoutOption from .uiautomator2_server_read_timeout_option import Uiautomator2ServerReadTimeoutOption class UiAutomator2Options( AppiumOptions, AppOption, ClearSystemFilesOption, OrientationOption, UdidOption, LanguageOption, LocaleOption, IsHeadlessOption, SkipLogCaptureOption, AutoWebViewOption, EnablePerformanceLoggingOption, OtherAppsOption, DeviceNameOption, SystemPortOption, SkipServerInstallationOption, Uiautomator2ServerInstallTimeoutOption, Uiautomator2ServerLaunchTimeoutOption, Uiautomator2ServerReadTimeoutOption, DisableWindowAnimationOption, SkipDeviceInitializationOption, AppPackageOption, AppActivityOption, AppWaitActivityOption, AppWaitPackageOption, AppWaitDurationOption, AndroidInstallTimeoutOption, AppWaitForLaunchOption, IntentCategoryOption, IntentActionOption, IntentFlagsOption, OptionalIntentArgumentsOption, AutoGrantPermissionsOption, UninstallOtherPackagesOption, AllowTestPackagesOption, RemoteAppsCacheLimitOption, EnforceAppInstallOption, LocaleScriptOption, AdbPortOption, RemoteAdbHostOption, AdbExecTimeoutOption, ClearDeviceLogsOnStartOption, SkipLogcatCaptureOption, BuildToolsVersionOption, SuppressKillServerOption, IgnoreHiddenApiPolicyErrorOption, MockLocationAppOption, LogcatFormatOption, LogcatFilterSpecsOption, AllowDelayAdbOption, AvdOption, AvdLaunchTimeoutOption, AvdReadyTimeoutOption, AvdArgsOption, AvdEnvOption, NetworkSpeedOption, GpsEnabledOption, UseKeystoreOption, KeystorePathOption, KeystorePasswordOption, KeyAliasOption, KeyPasswordOption, NoSignOption, SkipUnlockOption, UnlockKeyOption, UnlockStrategyOption, UnlockSuccessTimeoutOption, UnlockTypeOption, MjpegServerPortOption, MjpegScreenshotUrlOption, AutoWebviewTimeoutOption, ChromeLoggingPrefsOption, ChromeOptionsOption, ChromedriverArgsOption, ChromedriverChromeMappingFileOption, ChromedriverDisableBuildCheckOption, ChromedriverExecutableDirOption, ChromedriverExecutableOption, ChromedriverPortOption, ChromedriverPortsOption, ChromedriverUseSystemExecutableOption, EnsureWebviewsHavePagesOption, ExtractChromeAndroidPackageFromContextNameOption, NativeWebScreenshotOption, RecreateChromeDriverSessionsOption, ShowChromedriverLogOption, WebviewDevtoolsPortOption, DisableSuppressAccessibilityServiceOption, UserProfileOption, ): @property def default_capabilities(self) -> Dict: return { AUTOMATION_NAME: 'UIAutomator2', PLATFORM_NAME: 'Android', }
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/options/android/uiautomator2/base.py
base.py
from typing import Dict from appium.options.android.common.adb.adb_exec_timeout_option import AdbExecTimeoutOption from appium.options.android.common.adb.adb_port_option import AdbPortOption from appium.options.android.common.adb.allow_delay_adb_option import AllowDelayAdbOption from appium.options.android.common.adb.build_tools_version_option import BuildToolsVersionOption from appium.options.android.common.adb.clear_device_logs_on_start_option import ClearDeviceLogsOnStartOption from appium.options.android.common.adb.ignore_hidden_api_policy_error_option import IgnoreHiddenApiPolicyErrorOption from appium.options.android.common.adb.logcat_filter_specs_option import LogcatFilterSpecsOption from appium.options.android.common.adb.logcat_format_option import LogcatFormatOption from appium.options.android.common.adb.mock_location_app_option import MockLocationAppOption from appium.options.android.common.adb.remote_adb_host_option import RemoteAdbHostOption from appium.options.android.common.adb.skip_logcat_capture_option import SkipLogcatCaptureOption from appium.options.android.common.adb.suppress_kill_server_option import SuppressKillServerOption from appium.options.android.common.app.allow_test_packages_option import AllowTestPackagesOption from appium.options.android.common.app.android_install_timeout_option import AndroidInstallTimeoutOption from appium.options.android.common.app.app_activity_option import AppActivityOption from appium.options.android.common.app.app_package_option import AppPackageOption from appium.options.android.common.app.app_wait_activity_option import AppWaitActivityOption from appium.options.android.common.app.app_wait_duration_option import AppWaitDurationOption from appium.options.android.common.app.app_wait_for_launch_option import AppWaitForLaunchOption from appium.options.android.common.app.app_wait_package_option import AppWaitPackageOption from appium.options.android.common.app.auto_grant_premissions_option import AutoGrantPermissionsOption from appium.options.android.common.app.enforce_app_install_option import EnforceAppInstallOption from appium.options.android.common.app.intent_action_option import IntentActionOption from appium.options.android.common.app.intent_category_option import IntentCategoryOption from appium.options.android.common.app.intent_flags_option import IntentFlagsOption from appium.options.android.common.app.optional_intent_arguments_option import OptionalIntentArgumentsOption from appium.options.android.common.app.remote_apps_cache_limit_option import RemoteAppsCacheLimitOption from appium.options.android.common.app.uninstall_other_packages_option import UninstallOtherPackagesOption from appium.options.android.common.avd.avd_args_option import AvdArgsOption from appium.options.android.common.avd.avd_env_option import AvdEnvOption from appium.options.android.common.avd.avd_launch_timeout_option import AvdLaunchTimeoutOption from appium.options.android.common.avd.avd_option import AvdOption from appium.options.android.common.avd.avd_ready_timeout_option import AvdReadyTimeoutOption from appium.options.android.common.avd.gps_enabled_option import GpsEnabledOption from appium.options.android.common.avd.network_speed_option import NetworkSpeedOption from appium.options.android.common.context.auto_webview_timeout_option import AutoWebviewTimeoutOption from appium.options.android.common.context.chrome_logging_prefs_option import ChromeLoggingPrefsOption from appium.options.android.common.context.chrome_options_option import ChromeOptionsOption from appium.options.android.common.context.chromedriver_args_option import ChromedriverArgsOption from appium.options.android.common.context.chromedriver_chrome_mapping_file_option import ( ChromedriverChromeMappingFileOption, ) from appium.options.android.common.context.chromedriver_disable_build_check_option import ( ChromedriverDisableBuildCheckOption, ) from appium.options.android.common.context.chromedriver_executable_dir_option import ChromedriverExecutableDirOption from appium.options.android.common.context.chromedriver_executable_option import ChromedriverExecutableOption from appium.options.android.common.context.chromedriver_port_option import ChromedriverPortOption from appium.options.android.common.context.chromedriver_ports_option import ChromedriverPortsOption from appium.options.android.common.context.chromedriver_use_system_executable_option import ( ChromedriverUseSystemExecutableOption, ) from appium.options.android.common.context.ensure_webviews_have_pages_option import EnsureWebviewsHavePagesOption from appium.options.android.common.context.extract_chrome_android_package_from_context_name_option import ( ExtractChromeAndroidPackageFromContextNameOption, ) from appium.options.android.common.context.native_web_screenshot_option import NativeWebScreenshotOption from appium.options.android.common.context.recreate_chrome_driver_sessions_option import ( RecreateChromeDriverSessionsOption, ) from appium.options.android.common.context.show_chromedriver_log_option import ShowChromedriverLogOption from appium.options.android.common.context.webview_devtools_port_option import WebviewDevtoolsPortOption from appium.options.android.common.localization.locale_script_option import LocaleScriptOption from appium.options.android.common.locking.skip_unlock_option import SkipUnlockOption from appium.options.android.common.locking.unlock_key_option import UnlockKeyOption from appium.options.android.common.locking.unlock_strategy_option import UnlockStrategyOption from appium.options.android.common.locking.unlock_success_timeout_option import UnlockSuccessTimeoutOption from appium.options.android.common.locking.unlock_type_option import UnlockTypeOption from appium.options.android.common.mjpeg.mjpeg_screenshot_url_option import MjpegScreenshotUrlOption from appium.options.android.common.other.disable_suppress_accessibility_service_option import ( DisableSuppressAccessibilityServiceOption, ) from appium.options.android.common.other.user_profile_option import UserProfileOption from appium.options.android.common.signing.key_alias_option import KeyAliasOption from appium.options.android.common.signing.key_password_option import KeyPasswordOption from appium.options.android.common.signing.keystore_password_option import KeystorePasswordOption from appium.options.android.common.signing.keystore_path_option import KeystorePathOption from appium.options.android.common.signing.no_sign_option import NoSignOption from appium.options.android.common.signing.use_keystore_option import UseKeystoreOption from appium.options.common.app_option import AppOption from appium.options.common.auto_web_view_option import AutoWebViewOption from appium.options.common.automation_name_option import AUTOMATION_NAME from appium.options.common.base import PLATFORM_NAME, AppiumOptions from appium.options.common.clear_system_files_option import ClearSystemFilesOption from appium.options.common.device_name_option import DeviceNameOption from appium.options.common.enable_performance_logging_option import EnablePerformanceLoggingOption from appium.options.common.is_headless_option import IsHeadlessOption from appium.options.common.language_option import LanguageOption from appium.options.common.locale_option import LocaleOption from appium.options.common.orientation_option import OrientationOption from appium.options.common.other_apps_option import OtherAppsOption from appium.options.common.skip_log_capture_option import SkipLogCaptureOption from appium.options.common.system_port_option import SystemPortOption from appium.options.common.udid_option import UdidOption from .activity_options_option import ActivityOptionsOption from .app_locale_option import AppLocaleOption from .espresso_build_config_option import EspressoBuildConfigOption from .espresso_server_launch_timeout_option import EspressoServerLaunchTimeoutOption from .force_espresso_rebuild_option import ForceEspressoRebuildOption from .intent_options_option import IntentOptionsOption from .show_gradle_log_option import ShowGradleLogOption class EspressoOptions( AppiumOptions, AppOption, OrientationOption, UdidOption, LanguageOption, LocaleOption, IsHeadlessOption, SkipLogCaptureOption, AutoWebViewOption, DeviceNameOption, ClearSystemFilesOption, EnablePerformanceLoggingOption, OtherAppsOption, SystemPortOption, AppPackageOption, AppActivityOption, AppWaitActivityOption, AppWaitPackageOption, AppWaitDurationOption, AndroidInstallTimeoutOption, AppWaitForLaunchOption, IntentCategoryOption, IntentActionOption, IntentFlagsOption, OptionalIntentArgumentsOption, AutoGrantPermissionsOption, UninstallOtherPackagesOption, AllowTestPackagesOption, RemoteAppsCacheLimitOption, EnforceAppInstallOption, LocaleScriptOption, AdbPortOption, RemoteAdbHostOption, AdbExecTimeoutOption, ClearDeviceLogsOnStartOption, BuildToolsVersionOption, SkipLogcatCaptureOption, SuppressKillServerOption, IgnoreHiddenApiPolicyErrorOption, MockLocationAppOption, LogcatFormatOption, LogcatFilterSpecsOption, AllowDelayAdbOption, AvdOption, AvdLaunchTimeoutOption, AvdReadyTimeoutOption, AvdArgsOption, AvdEnvOption, NetworkSpeedOption, GpsEnabledOption, UseKeystoreOption, KeystorePathOption, KeystorePasswordOption, KeyAliasOption, KeyPasswordOption, NoSignOption, SkipUnlockOption, UnlockKeyOption, UnlockStrategyOption, UnlockSuccessTimeoutOption, UnlockTypeOption, MjpegScreenshotUrlOption, AutoWebviewTimeoutOption, ChromeLoggingPrefsOption, ChromeOptionsOption, ChromedriverArgsOption, ChromedriverChromeMappingFileOption, ChromedriverDisableBuildCheckOption, ChromedriverExecutableDirOption, ChromedriverExecutableOption, ChromedriverPortOption, ChromedriverPortsOption, ChromedriverUseSystemExecutableOption, EnsureWebviewsHavePagesOption, ExtractChromeAndroidPackageFromContextNameOption, NativeWebScreenshotOption, RecreateChromeDriverSessionsOption, ShowChromedriverLogOption, WebviewDevtoolsPortOption, DisableSuppressAccessibilityServiceOption, UserProfileOption, EspressoBuildConfigOption, EspressoServerLaunchTimeoutOption, ForceEspressoRebuildOption, ShowGradleLogOption, IntentOptionsOption, ActivityOptionsOption, AppLocaleOption, ): @property def default_capabilities(self) -> Dict: return { AUTOMATION_NAME: 'Espresso', PLATFORM_NAME: 'Android', }
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/options/android/espresso/base.py
base.py
from typing import Dict from appium.options.common.app_option import AppOption from appium.options.common.auto_web_view_option import AutoWebViewOption from appium.options.common.automation_name_option import AUTOMATION_NAME from appium.options.common.base import PLATFORM_NAME, AppiumOptions from appium.options.common.bundle_id_option import BundleIdOption from appium.options.common.clear_system_files_option import ClearSystemFilesOption from appium.options.common.device_name_option import DeviceNameOption from appium.options.common.enable_performance_logging_option import EnablePerformanceLoggingOption from appium.options.common.is_headless_option import IsHeadlessOption from appium.options.common.language_option import LanguageOption from appium.options.common.locale_option import LocaleOption from appium.options.common.orientation_option import OrientationOption from appium.options.common.other_apps_option import OtherAppsOption from appium.options.common.skip_log_capture_option import SkipLogCaptureOption from appium.options.common.udid_option import UdidOption from .app.app_install_strategy_option import AppInstallStrategyOption from .app.app_push_timeout_option import AppPushTimeoutOption from .app.localizable_strings_dir_option import LocalizableStringsDirOption from .general.include_device_caps_to_session_info_option import IncludeDeviceCapsToSessionInfoOption from .general.reset_location_service_option import ResetLocationServiceOption from .other.command_timeouts_option import CommandTimeoutsOption from .other.launch_with_idb_option import LaunchWithIdbOption from .other.show_ios_log_option import ShowIosLogOption from .other.use_json_source_option import UseJsonSourceOption from .simulator.calendar_access_authorized_option import CalendarAccessAuthorizedOption from .simulator.calendar_format_option import CalendarFormatOption from .simulator.connect_hardware_keyboard_option import ConnectHardwareKeyboardOption from .simulator.custom_ssl_cert_option import CustomSslCertOption from .simulator.enforce_fresh_simulator_creation_option import EnforceFreshSimulatorCreationOption from .simulator.force_simulator_software_keyboard_presence_option import ForceSimulatorSoftwareKeyboardPresenceOption from .simulator.ios_simulator_logs_predicate_option import IosSimulatorLogsPredicateOption from .simulator.keep_key_chains_option import KeepKeyChainsOption from .simulator.keychains_exclude_patterns_option import KeychainsExcludePatternsOption from .simulator.permissions_option import PermissionsOption from .simulator.reduce_motion_option import ReduceMotionOption from .simulator.reset_on_session_start_only_option import ResetOnSessionStartOnlyOption from .simulator.scale_factor_option import ScaleFactorOption from .simulator.shutdown_other_simulators_option import ShutdownOtherSimulatorsOption from .simulator.simulator_devices_set_path_option import SimulatorDevicesSetPathOption from .simulator.simulator_pasteboard_automatic_sync_option import SimulatorPasteboardAutomaticSyncOption from .simulator.simulator_startup_timeout_option import SimulatorStartupTimeoutOption from .simulator.simulator_trace_pointer_option import SimulatorTracePointerOption from .simulator.simulator_window_center_option import SimulatorWindowCenterOption from .wda.allow_provisioning_device_regitration_option import AllowProvisioningDeviceRegistrationOption from .wda.auto_accept_alerts_option import AutoAcceptAlertsOption from .wda.auto_disimiss_alerts_option import AutoDismissAlertsOption from .wda.derived_data_path_option import DerivedDataPathOption from .wda.disable_automatic_screenshots_option import DisableAutomaticScreenshotsOption from .wda.force_app_launch_option import ForceAppLaunchOption from .wda.keychain_password_option import KeychainPasswordOption from .wda.keychain_path_option import KeychainPathOption from .wda.max_typing_frequency_option import MaxTypingFrequencyOption from .wda.mjpeg_server_port_option import MjpegServerPortOption from .wda.process_arguments_option import ProcessArgumentsOption from .wda.result_bundle_path_option import ResultBundlePathOption from .wda.screenshot_quality_option import ScreenshotQualityOption from .wda.should_terminate_app_option import ShouldTerminateAppOption from .wda.should_use_singleton_test_manager_option import ShouldUseSingletonTestManagerOption from .wda.show_xcode_log_option import ShowXcodeLogOption from .wda.simple_is_visible_check_option import SimpleIsVisibleCheckOption from .wda.updated_wda_bundle_id_option import UpdatedWdaBundleIdOption from .wda.use_native_caching_strategy_option import UseNativeCachingStrategyOption from .wda.use_new_wda_option import UseNewWdaOption from .wda.use_prebuilt_wda_option import UsePrebuiltWdaOption from .wda.use_simple_build_test_option import UseSimpleBuildTestOption from .wda.use_xctestrun_file_option import UseXctestrunFileOption from .wda.wait_for_idle_timeout_option import WaitForIdleTimeoutOption from .wda.wait_for_quiescence_option import WaitForQuiescenceOption from .wda.wda_base_url_option import WdaBaseUrlOption from .wda.wda_connection_timeout_option import WdaConnectionTimeoutOption from .wda.wda_eventloop_idle_delay_option import WdaEventloopIdleDelayOption from .wda.wda_launch_timeout_option import WdaLaunchTimeoutOption from .wda.wda_local_port_option import WdaLocalPortOption from .wda.wda_startup_retries_option import WdaStartupRetriesOption from .wda.wda_startup_retry_interval_option import WdaStartupRetryIntervalOption from .wda.web_driver_agent_url_option import WebDriverAgentUrlOption from .wda.xcode_org_id_option import XcodeOrgIdOption from .wda.xcode_signing_id_option import XcodeSigningIdOption from .webview.absolute_web_locations_option import AbsoluteWebLocationsOption from .webview.additional_webview_bundle_ids_option import AdditionalWebviewBundleIdsOption from .webview.enable_async_execute_from_https_option import EnableAsyncExecuteFromHttpsOption from .webview.full_context_list_option import FullContextListOption from .webview.include_safari_in_webviews_option import IncludeSafariInWebviewsOption from .webview.native_web_tap_option import NativeWebTapOption from .webview.safari_garbage_collect_option import SafariGarbageCollectOption from .webview.safari_ignore_fraud_warning_option import SafariIgnoreFraudWarningOption from .webview.safari_ignore_web_hostnames_option import SafariIgnoreWebHostnamesOption from .webview.safari_initial_url_option import SafariInitialUrlOption from .webview.safari_log_all_communication_hex_dump_option import SafariLogAllCommunicationHexDumpOption from .webview.safari_log_all_communication_option import SafariLogAllCommunicationOption from .webview.safari_open_links_in_background_option import SafariOpenLinksInBackgroundOption from .webview.safari_socket_chunk_size_option import SafariSocketChunkSizeOption from .webview.safari_web_inspector_max_frame_length_option import SafariWebInspectorMaxFrameLengthOption from .webview.webkit_response_timeout_option import WebkitResponseTimeoutOption from .webview.webview_connect_retries_option import WebviewConnectRetriesOption from .webview.webview_connect_timeout_option import WebviewConnectTimeoutOption class XCUITestOptions( AppiumOptions, AppOption, BundleIdOption, ClearSystemFilesOption, OrientationOption, UdidOption, LanguageOption, LocaleOption, IsHeadlessOption, SkipLogCaptureOption, AutoWebViewOption, EnablePerformanceLoggingOption, OtherAppsOption, DeviceNameOption, IncludeDeviceCapsToSessionInfoOption, ResetLocationServiceOption, AppInstallStrategyOption, AppPushTimeoutOption, LocalizableStringsDirOption, CommandTimeoutsOption, LaunchWithIdbOption, ShowIosLogOption, UseJsonSourceOption, CalendarAccessAuthorizedOption, CalendarFormatOption, ConnectHardwareKeyboardOption, CustomSslCertOption, EnforceFreshSimulatorCreationOption, ForceSimulatorSoftwareKeyboardPresenceOption, IosSimulatorLogsPredicateOption, KeepKeyChainsOption, KeychainsExcludePatternsOption, PermissionsOption, ReduceMotionOption, ResetOnSessionStartOnlyOption, ScaleFactorOption, ShutdownOtherSimulatorsOption, SimulatorDevicesSetPathOption, SimulatorPasteboardAutomaticSyncOption, SimulatorStartupTimeoutOption, SimulatorTracePointerOption, SimulatorWindowCenterOption, AllowProvisioningDeviceRegistrationOption, AutoAcceptAlertsOption, AutoDismissAlertsOption, DerivedDataPathOption, DisableAutomaticScreenshotsOption, ForceAppLaunchOption, KeychainPasswordOption, KeychainPathOption, MaxTypingFrequencyOption, MjpegServerPortOption, ProcessArgumentsOption, ResultBundlePathOption, ScreenshotQualityOption, ShouldTerminateAppOption, ShouldUseSingletonTestManagerOption, ShowXcodeLogOption, SimpleIsVisibleCheckOption, UpdatedWdaBundleIdOption, UseNativeCachingStrategyOption, UseNewWdaOption, UsePrebuiltWdaOption, UseSimpleBuildTestOption, UseXctestrunFileOption, WaitForIdleTimeoutOption, WaitForQuiescenceOption, WdaBaseUrlOption, WdaConnectionTimeoutOption, WdaEventloopIdleDelayOption, WdaLaunchTimeoutOption, WdaLocalPortOption, WdaStartupRetriesOption, WdaStartupRetryIntervalOption, WebDriverAgentUrlOption, XcodeOrgIdOption, XcodeSigningIdOption, AbsoluteWebLocationsOption, AdditionalWebviewBundleIdsOption, EnableAsyncExecuteFromHttpsOption, FullContextListOption, IncludeSafariInWebviewsOption, NativeWebTapOption, SafariGarbageCollectOption, SafariIgnoreFraudWarningOption, SafariIgnoreWebHostnamesOption, SafariInitialUrlOption, SafariLogAllCommunicationHexDumpOption, SafariLogAllCommunicationOption, SafariOpenLinksInBackgroundOption, SafariSocketChunkSizeOption, SafariWebInspectorMaxFrameLengthOption, WebkitResponseTimeoutOption, WebviewConnectRetriesOption, WebviewConnectTimeoutOption, ): @property def default_capabilities(self) -> Dict: return { AUTOMATION_NAME: 'XCUITest', PLATFORM_NAME: 'iOS', }
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/options/ios/xcuitest/base.py
base.py
from typing import Dict from appium.options.common.automation_name_option import AUTOMATION_NAME from appium.options.common.base import PLATFORM_NAME, AppiumOptions from appium.options.common.bundle_id_option import BundleIdOption from appium.options.common.postrun_option import PostrunOption from appium.options.common.prerun_option import PrerunOption from appium.options.common.system_host_option import SystemHostOption from appium.options.common.system_port_option import SystemPortOption from .arguments_option import ArgumentsOption from .bootstrap_root_option import BootstrapRootOption from .environment_option import EnvironmentOption from .server_startup_timeout_option import ServerStartupTimeoutOption from .show_server_logs_option import ShowServerLogsOption from .skip_app_kill_option import SkipAppKillOption from .web_driver_agent_mac_url_option import WebDriverAgentMacUrlOption class Mac2Options( AppiumOptions, PrerunOption, PostrunOption, ArgumentsOption, BootstrapRootOption, BundleIdOption, EnvironmentOption, ServerStartupTimeoutOption, ShowServerLogsOption, SkipAppKillOption, SystemHostOption, SystemPortOption, WebDriverAgentMacUrlOption, ): @PrerunOption.prerun.setter # type: ignore def prerun(self, value: Dict[str, str]) -> None: """ A mapping containing either 'script' or 'command' key. The value of each key must be a valid AppleScript script or command to be executed after before Mac2Driver session is started. See https://github.com/appium/appium-mac2-driver#applescript-commands-execution for more details. """ PrerunOption.prerun.fset(self, value) # type: ignore @PostrunOption.postrun.setter # type: ignore def postrun(self, value: Dict[str, str]) -> None: """ A mapping containing either 'script' or 'command' key. The value of each key must be a valid AppleScript script or command to be executed after Mac2Driver session is stopped. See https://github.com/appium/appium-mac2-driver#applescript-commands-execution for more details. """ PostrunOption.postrun.fset(self, value) # type: ignore @SystemPortOption.system_port.setter # type: ignore def system_port(self, value: int) -> None: """ Set the number of the port for the internal server to listen on. If not provided then Mac2Driver will use the default port 10100. """ SystemPortOption.system_port.fset(self, value) # type: ignore @SystemHostOption.system_host.setter # type: ignore def system_host(self, value: str) -> None: """ Set the number of the port for the internal server to listen on. If not provided then Mac2Driver will use the default host address 127.0.0.1. You could set it to 0.0.0.0 to make the server listening on all available network interfaces. It is also possible to set the particular interface name, for example en1. """ SystemHostOption.system_host.fset(self, value) # type: ignore @BundleIdOption.bundle_id.setter # type: ignore def bundle_id(self, value: str) -> None: """ Set the bundle identifier of the application to automate, for example com.apple.TextEdit. This is an optional capability. If it is not provided then the session will be started without an application under test (actually, it will be Finder). If the application with the given identifier is not installed then an error will be thrown on session startup. If the application is already running then it will be moved to the foreground. """ BundleIdOption.bundle_id.fset(self, value) # type: ignore @property def default_capabilities(self) -> Dict: return { AUTOMATION_NAME: 'Mac2', PLATFORM_NAME: 'Mac', }
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/options/mac/mac2/base.py
base.py
import copy from typing import Any, Dict, TypeVar from selenium.webdriver.common.options import BaseOptions from .automation_name_option import AutomationNameOption from .event_timings_option import EventTimingsOption from .full_reset_option import FullResetOption from .new_command_timeout_option import NewCommandTimeoutOption from .no_reset_option import NoResetOption from .print_page_source_on_find_failure_option import PrintPageSourceOnFindFailureOption APPIUM_PREFIX = 'appium:' T = TypeVar('T', bound='AppiumOptions') PLATFORM_NAME = 'platformName' class AppiumOptions( BaseOptions, AutomationNameOption, EventTimingsOption, PrintPageSourceOnFindFailureOption, NoResetOption, FullResetOption, NewCommandTimeoutOption, ): _caps: Dict W3C_CAPABILITY_NAMES = frozenset( [ 'acceptInsecureCerts', 'browserName', 'browserVersion', PLATFORM_NAME, 'pageLoadStrategy', 'proxy', 'setWindowRect', 'timeouts', 'unhandledPromptBehavior', ] ) _OSS_W3C_CONVERSION = { 'acceptSslCerts': 'acceptInsecureCerts', 'version': 'browserVersion', 'platform': PLATFORM_NAME, } # noinspection PyMissingConstructor def __init__(self) -> None: self._caps = self.default_capabilities # FIXME: https://github.com/SeleniumHQ/selenium/issues/10755 self._ignore_local_proxy = False def set_capability(self: T, name: str, value: Any) -> T: w3c_name = name if name in self.W3C_CAPABILITY_NAMES or ':' in name else f'{APPIUM_PREFIX}{name}' if value is None: if w3c_name in self._caps: del self._caps[w3c_name] else: self._caps[w3c_name] = value return self def get_capability(self, name: str) -> Any: """Fetches capability value or None if the capability is not set""" return self._caps[name] if name in self._caps else self._caps.get(f'{APPIUM_PREFIX}{name}') def load_capabilities(self: T, caps: Dict[str, Any]) -> T: """Sets multiple capabilities""" for name, value in caps.items(): self.set_capability(name, value) return self @staticmethod def as_w3c(capabilities: Dict) -> Dict: """ Formats given capabilities to a valid W3C session request object :param capabilities: Capabilities mapping :return: W3C session request object """ def process_key(k: str) -> str: key = AppiumOptions._OSS_W3C_CONVERSION.get(k, k) if key in AppiumOptions.W3C_CAPABILITY_NAMES: return key return key if ':' in key else f'{APPIUM_PREFIX}{key}' processed_caps = {process_key(k): v for k, v in copy.deepcopy(capabilities).items()} return {'capabilities': {'firstMatch': [{}], 'alwaysMatch': processed_caps}} def to_w3c(self) -> Dict: """ Formats the instance to a valid W3C session request object :return: W3C session request object """ return self.as_w3c(self.to_capabilities()) def to_capabilities(self) -> Dict: return copy.copy(self._caps) @property def default_capabilities(self) -> Dict: return {}
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/appium/options/common/base.py
base.py
webdriver.extensions.search\_context package ============================================ Submodules ---------- webdriver.extensions.search\_context.android module --------------------------------------------------- .. automodule:: webdriver.extensions.search_context.android :members: :undoc-members: :show-inheritance: webdriver.extensions.search\_context.base\_search\_context module ----------------------------------------------------------------- .. automodule:: webdriver.extensions.search_context.base_search_context :members: :undoc-members: :show-inheritance: webdriver.extensions.search\_context.custom module -------------------------------------------------- .. automodule:: webdriver.extensions.search_context.custom :members: :undoc-members: :show-inheritance: webdriver.extensions.search\_context.ios module ----------------------------------------------- .. automodule:: webdriver.extensions.search_context.ios :members: :undoc-members: :show-inheritance: webdriver.extensions.search\_context.mobile module -------------------------------------------------- .. automodule:: webdriver.extensions.search_context.mobile :members: :undoc-members: :show-inheritance: webdriver.extensions.search\_context.windows module --------------------------------------------------- .. automodule:: webdriver.extensions.search_context.windows :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: webdriver.extensions.search_context :members: :undoc-members: :show-inheritance:
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/webdriver.extensions.search_context.rst
webdriver.extensions.search_context.rst
webdriver.extensions.android package ==================================== Submodules ---------- webdriver.extensions.android.activities module ---------------------------------------------- .. automodule:: webdriver.extensions.android.activities :members: :undoc-members: :show-inheritance: webdriver.extensions.android.common module ------------------------------------------ .. automodule:: webdriver.extensions.android.common :members: :undoc-members: :show-inheritance: webdriver.extensions.android.display module ------------------------------------------- .. automodule:: webdriver.extensions.android.display :members: :undoc-members: :show-inheritance: webdriver.extensions.android.gsm module --------------------------------------- .. automodule:: webdriver.extensions.android.gsm :members: :undoc-members: :show-inheritance: webdriver.extensions.android.nativekey module --------------------------------------------- .. automodule:: webdriver.extensions.android.nativekey :members: :undoc-members: :show-inheritance: webdriver.extensions.android.network module ------------------------------------------- .. automodule:: webdriver.extensions.android.network :members: :undoc-members: :show-inheritance: webdriver.extensions.android.performance module ----------------------------------------------- .. automodule:: webdriver.extensions.android.performance :members: :undoc-members: :show-inheritance: webdriver.extensions.android.power module ----------------------------------------- .. automodule:: webdriver.extensions.android.power :members: :undoc-members: :show-inheritance: webdriver.extensions.android.sms module --------------------------------------- .. automodule:: webdriver.extensions.android.sms :members: :undoc-members: :show-inheritance: webdriver.extensions.android.system\_bars module ------------------------------------------------ .. automodule:: webdriver.extensions.android.system_bars :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: webdriver.extensions.android :members: :undoc-members: :show-inheritance:
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/webdriver.extensions.android.rst
webdriver.extensions.android.rst
webdriver package ================= Subpackages ----------- .. toctree:: :maxdepth: 4 webdriver.common webdriver.extensions Submodules ---------- webdriver.appium\_connection module ----------------------------------- .. automodule:: webdriver.appium_connection :members: :undoc-members: :show-inheritance: webdriver.appium\_service module -------------------------------- .. automodule:: webdriver.appium_service :members: :undoc-members: :show-inheritance: webdriver.applicationstate module --------------------------------- .. automodule:: webdriver.applicationstate :members: :undoc-members: :show-inheritance: webdriver.clipboard\_content\_type module ----------------------------------------- .. automodule:: webdriver.clipboard_content_type :members: :undoc-members: :show-inheritance: webdriver.connectiontype module ------------------------------- .. automodule:: webdriver.connectiontype :members: :undoc-members: :show-inheritance: webdriver.errorhandler module ----------------------------- .. automodule:: webdriver.errorhandler :members: :undoc-members: :show-inheritance: webdriver.mobilecommand module ------------------------------ .. automodule:: webdriver.mobilecommand :members: :undoc-members: :show-inheritance: webdriver.switch\_to module --------------------------- .. automodule:: webdriver.switch_to :members: :undoc-members: :show-inheritance: webdriver.webdriver module -------------------------- .. automodule:: webdriver.webdriver :members: :undoc-members: :show-inheritance: webdriver.webelement module --------------------------- .. automodule:: webdriver.webelement :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: webdriver :members: :undoc-members: :show-inheritance:
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/webdriver.rst
webdriver.rst
webdriver.common package ======================== Submodules ---------- webdriver.common.mobileby module -------------------------------- .. automodule:: webdriver.common.mobileby :members: :undoc-members: :show-inheritance: webdriver.common.multi\_action module ------------------------------------- .. automodule:: webdriver.common.multi_action :members: :undoc-members: :show-inheritance: webdriver.common.touch\_action module ------------------------------------- .. automodule:: webdriver.common.touch_action :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: webdriver.common :members: :undoc-members: :show-inheritance:
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/webdriver.common.rst
webdriver.common.rst
webdriver.extensions package ============================ Subpackages ----------- .. toctree:: :maxdepth: 4 webdriver.extensions.android webdriver.extensions.search_context Submodules ---------- webdriver.extensions.action\_helpers module ------------------------------------------- .. automodule:: webdriver.extensions.action_helpers :members: :undoc-members: :show-inheritance: webdriver.extensions.applications module ---------------------------------------- .. automodule:: webdriver.extensions.applications :members: :undoc-members: :show-inheritance: webdriver.extensions.clipboard module ------------------------------------- .. automodule:: webdriver.extensions.clipboard :members: :undoc-members: :show-inheritance: webdriver.extensions.context module ----------------------------------- .. automodule:: webdriver.extensions.context :members: :undoc-members: :show-inheritance: webdriver.extensions.device\_time module ---------------------------------------- .. automodule:: webdriver.extensions.device_time :members: :undoc-members: :show-inheritance: webdriver.extensions.execute\_driver module ------------------------------------------- .. automodule:: webdriver.extensions.execute_driver :members: :undoc-members: :show-inheritance: webdriver.extensions.execute\_mobile\_command module ---------------------------------------------------- .. automodule:: webdriver.extensions.execute_mobile_command :members: :undoc-members: :show-inheritance: webdriver.extensions.hw\_actions module --------------------------------------- .. automodule:: webdriver.extensions.hw_actions :members: :undoc-members: :show-inheritance: webdriver.extensions.images\_comparison module ---------------------------------------------- .. automodule:: webdriver.extensions.images_comparison :members: :undoc-members: :show-inheritance: webdriver.extensions.ime module ------------------------------- .. automodule:: webdriver.extensions.ime :members: :undoc-members: :show-inheritance: webdriver.extensions.keyboard module ------------------------------------ .. automodule:: webdriver.extensions.keyboard :members: :undoc-members: :show-inheritance: webdriver.extensions.location module ------------------------------------ .. automodule:: webdriver.extensions.location :members: :undoc-members: :show-inheritance: webdriver.extensions.log\_event module -------------------------------------- .. automodule:: webdriver.extensions.log_event :members: :undoc-members: :show-inheritance: webdriver.extensions.remote\_fs module -------------------------------------- .. automodule:: webdriver.extensions.remote_fs :members: :undoc-members: :show-inheritance: webdriver.extensions.screen\_record module ------------------------------------------ .. automodule:: webdriver.extensions.screen_record :members: :undoc-members: :show-inheritance: webdriver.extensions.session module ----------------------------------- .. automodule:: webdriver.extensions.session :members: :undoc-members: :show-inheritance: webdriver.extensions.settings module ------------------------------------ .. automodule:: webdriver.extensions.settings :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: webdriver.extensions :members: :undoc-members: :show-inheritance:
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/webdriver.extensions.rst
webdriver.extensions.rst
Search.setIndex({docnames:["appium","appium.common","appium.webdriver","appium.webdriver.common","appium.webdriver.extensions","appium.webdriver.extensions.android","appium.webdriver.extensions.search_context","index"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":4,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":3,"sphinx.domains.rst":2,"sphinx.domains.std":2,sphinx:56},filenames:["appium.rst","appium.common.rst","appium.webdriver.rst","appium.webdriver.common.rst","appium.webdriver.extensions.rst","appium.webdriver.extensions.android.rst","appium.webdriver.extensions.search_context.rst","index.rst"],objects:{"":[[0,0,0,"-","appium"]],"appium.common":[[1,0,0,"-","exceptions"],[1,0,0,"-","helper"],[1,0,0,"-","logger"]],"appium.common.exceptions":[[1,1,1,"","NoSuchContextException"]],"appium.common.helper":[[1,2,1,"","extract_const_attributes"],[1,2,1,"","library_version"]],"appium.common.logger":[[1,2,1,"","setup_logger"]],"appium.webdriver":[[2,0,0,"-","appium_connection"],[2,0,0,"-","appium_service"],[2,0,0,"-","applicationstate"],[2,0,0,"-","clipboard_content_type"],[2,0,0,"-","command_method"],[3,0,0,"-","common"],[2,0,0,"-","connectiontype"],[2,0,0,"-","errorhandler"],[4,0,0,"-","extensions"],[2,0,0,"-","mobilecommand"],[2,0,0,"-","switch_to"],[2,0,0,"-","webdriver"],[2,0,0,"-","webelement"]],"appium.webdriver.appium_connection":[[2,3,1,"","AppiumConnection"]],"appium.webdriver.appium_connection.AppiumConnection":[[2,4,1,"","get_remote_connection_headers"]],"appium.webdriver.appium_service":[[2,3,1,"","AppiumService"],[2,1,1,"","AppiumServiceError"],[2,2,1,"","find_executable"],[2,2,1,"","poll_url"]],"appium.webdriver.appium_service.AppiumService":[[2,5,1,"","is_listening"],[2,5,1,"","is_running"],[2,4,1,"","start"],[2,4,1,"","stop"]],"appium.webdriver.applicationstate":[[2,3,1,"","ApplicationState"]],"appium.webdriver.applicationstate.ApplicationState":[[2,6,1,"","NOT_INSTALLED"],[2,6,1,"","NOT_RUNNING"],[2,6,1,"","RUNNING_IN_BACKGROUND"],[2,6,1,"","RUNNING_IN_BACKGROUND_SUSPENDED"],[2,6,1,"","RUNNING_IN_FOREGROUND"]],"appium.webdriver.clipboard_content_type":[[2,3,1,"","ClipboardContentType"]],"appium.webdriver.clipboard_content_type.ClipboardContentType":[[2,6,1,"","IMAGE"],[2,6,1,"","PLAINTEXT"],[2,6,1,"","URL"]],"appium.webdriver.command_method":[[2,3,1,"","CommandMethod"]],"appium.webdriver.command_method.CommandMethod":[[2,6,1,"","CONNECT"],[2,6,1,"","DELETE"],[2,6,1,"","GET"],[2,6,1,"","HEAD"],[2,6,1,"","OPTIONS"],[2,6,1,"","PATCH"],[2,6,1,"","POST"],[2,6,1,"","PUT"],[2,6,1,"","TRACE"]],"appium.webdriver.common":[[3,0,0,"-","mobileby"],[3,0,0,"-","multi_action"],[3,0,0,"-","touch_action"]],"appium.webdriver.common.mobileby":[[3,3,1,"","MobileBy"]],"appium.webdriver.common.mobileby.MobileBy":[[3,6,1,"","ACCESSIBILITY_ID"],[3,6,1,"","ANDROID_DATA_MATCHER"],[3,6,1,"","ANDROID_UIAUTOMATOR"],[3,6,1,"","ANDROID_VIEWTAG"],[3,6,1,"","ANDROID_VIEW_MATCHER"],[3,6,1,"","CUSTOM"],[3,6,1,"","IMAGE"],[3,6,1,"","IOS_CLASS_CHAIN"],[3,6,1,"","IOS_PREDICATE"],[3,6,1,"","IOS_UIAUTOMATION"],[3,6,1,"","WINDOWS_UI_AUTOMATION"]],"appium.webdriver.common.multi_action":[[3,3,1,"","MultiAction"]],"appium.webdriver.common.multi_action.MultiAction":[[3,4,1,"","add"],[3,5,1,"","json_wire_gestures"],[3,4,1,"","perform"]],"appium.webdriver.common.touch_action":[[3,3,1,"","TouchAction"]],"appium.webdriver.common.touch_action.TouchAction":[[3,5,1,"","json_wire_gestures"],[3,4,1,"","long_press"],[3,4,1,"","move_to"],[3,4,1,"","perform"],[3,4,1,"","press"],[3,4,1,"","release"],[3,4,1,"","tap"],[3,4,1,"","wait"]],"appium.webdriver.connectiontype":[[2,3,1,"","ConnectionType"]],"appium.webdriver.connectiontype.ConnectionType":[[2,6,1,"","AIRPLANE_MODE"],[2,6,1,"","ALL_NETWORK_ON"],[2,6,1,"","DATA_ONLY"],[2,6,1,"","NO_CONNECTION"],[2,6,1,"","WIFI_ONLY"]],"appium.webdriver.errorhandler":[[2,3,1,"","MobileErrorHandler"]],"appium.webdriver.errorhandler.MobileErrorHandler":[[2,4,1,"","check_response"]],"appium.webdriver.extensions":[[4,0,0,"-","action_helpers"],[5,0,0,"-","android"],[4,0,0,"-","applications"],[4,0,0,"-","clipboard"],[4,0,0,"-","context"],[4,0,0,"-","device_time"],[4,0,0,"-","execute_driver"],[4,0,0,"-","execute_mobile_command"],[4,0,0,"-","hw_actions"],[4,0,0,"-","images_comparison"],[4,0,0,"-","ime"],[4,0,0,"-","keyboard"],[4,0,0,"-","location"],[4,0,0,"-","log_event"],[4,0,0,"-","remote_fs"],[4,0,0,"-","screen_record"],[6,0,0,"-","search_context"],[4,0,0,"-","session"],[4,0,0,"-","settings"]],"appium.webdriver.extensions.action_helpers":[[4,3,1,"","ActionHelpers"]],"appium.webdriver.extensions.action_helpers.ActionHelpers":[[4,4,1,"","drag_and_drop"],[4,4,1,"","flick"],[4,4,1,"","scroll"],[4,4,1,"","swipe"],[4,4,1,"","tap"]],"appium.webdriver.extensions.android":[[5,0,0,"-","activities"],[5,0,0,"-","common"],[5,0,0,"-","display"],[5,0,0,"-","gsm"],[5,0,0,"-","nativekey"],[5,0,0,"-","network"],[5,0,0,"-","performance"],[5,0,0,"-","power"],[5,0,0,"-","sms"],[5,0,0,"-","system_bars"]],"appium.webdriver.extensions.android.activities":[[5,3,1,"","Activities"]],"appium.webdriver.extensions.android.activities.Activities":[[5,5,1,"","current_activity"],[5,4,1,"","start_activity"],[5,4,1,"","wait_activity"]],"appium.webdriver.extensions.android.common":[[5,3,1,"","Common"]],"appium.webdriver.extensions.android.common.Common":[[5,5,1,"","current_package"],[5,4,1,"","end_test_coverage"],[5,4,1,"","open_notifications"]],"appium.webdriver.extensions.android.display":[[5,3,1,"","Display"]],"appium.webdriver.extensions.android.display.Display":[[5,4,1,"","get_display_density"]],"appium.webdriver.extensions.android.gsm":[[5,3,1,"","Gsm"],[5,3,1,"","GsmCallActions"],[5,3,1,"","GsmSignalStrength"],[5,3,1,"","GsmVoiceState"]],"appium.webdriver.extensions.android.gsm.Gsm":[[5,4,1,"","make_gsm_call"],[5,4,1,"","set_gsm_signal"],[5,4,1,"","set_gsm_voice"]],"appium.webdriver.extensions.android.gsm.GsmCallActions":[[5,6,1,"","ACCEPT"],[5,6,1,"","CALL"],[5,6,1,"","CANCEL"],[5,6,1,"","HOLD"]],"appium.webdriver.extensions.android.gsm.GsmSignalStrength":[[5,6,1,"","GOOD"],[5,6,1,"","GREAT"],[5,6,1,"","MODERATE"],[5,6,1,"","NONE_OR_UNKNOWN"],[5,6,1,"","POOR"]],"appium.webdriver.extensions.android.gsm.GsmVoiceState":[[5,6,1,"","DENIED"],[5,6,1,"","HOME"],[5,6,1,"","OFF"],[5,6,1,"","ON"],[5,6,1,"","ROAMING"],[5,6,1,"","SEARCHING"],[5,6,1,"","UNREGISTERED"]],"appium.webdriver.extensions.android.nativekey":[[5,3,1,"","AndroidKey"]],"appium.webdriver.extensions.android.nativekey.AndroidKey":[[5,6,1,"","A"],[5,6,1,"","ALT_LEFT"],[5,6,1,"","ALT_RIGHT"],[5,6,1,"","APOSTROPHE"],[5,6,1,"","APP_SWITCH"],[5,6,1,"","ASSIST"],[5,6,1,"","AT"],[5,6,1,"","AVR_INPUT"],[5,6,1,"","AVR_POWER"],[5,6,1,"","B"],[5,6,1,"","BACK"],[5,6,1,"","BACKSLASH"],[5,6,1,"","BOOKMARK"],[5,6,1,"","BREAK"],[5,6,1,"","BRIGHTNESS_DOWN"],[5,6,1,"","BRIGHTNESS_UP"],[5,6,1,"","BUTTON_1"],[5,6,1,"","BUTTON_10"],[5,6,1,"","BUTTON_11"],[5,6,1,"","BUTTON_12"],[5,6,1,"","BUTTON_13"],[5,6,1,"","BUTTON_14"],[5,6,1,"","BUTTON_15"],[5,6,1,"","BUTTON_16"],[5,6,1,"","BUTTON_2"],[5,6,1,"","BUTTON_3"],[5,6,1,"","BUTTON_4"],[5,6,1,"","BUTTON_5"],[5,6,1,"","BUTTON_6"],[5,6,1,"","BUTTON_7"],[5,6,1,"","BUTTON_8"],[5,6,1,"","BUTTON_9"],[5,6,1,"","BUTTON_A"],[5,6,1,"","BUTTON_B"],[5,6,1,"","BUTTON_C"],[5,6,1,"","BUTTON_L1"],[5,6,1,"","BUTTON_L2"],[5,6,1,"","BUTTON_MODE"],[5,6,1,"","BUTTON_R1"],[5,6,1,"","BUTTON_R2"],[5,6,1,"","BUTTON_SELECT"],[5,6,1,"","BUTTON_START"],[5,6,1,"","BUTTON_THUMBL"],[5,6,1,"","BUTTON_THUMBR"],[5,6,1,"","BUTTON_X"],[5,6,1,"","BUTTON_Y"],[5,6,1,"","BUTTON_Z"],[5,6,1,"","C"],[5,6,1,"","CALCULATOR"],[5,6,1,"","CALENDAR"],[5,6,1,"","CALL"],[5,6,1,"","CAMERA"],[5,6,1,"","CAPS_LOCK"],[5,6,1,"","CAPTIONS"],[5,6,1,"","CHANNEL_DOWN"],[5,6,1,"","CHANNEL_UP"],[5,6,1,"","CLEAR"],[5,6,1,"","COMMA"],[5,6,1,"","CONTACTS"],[5,6,1,"","COPY"],[5,6,1,"","CTRL_LEFT"],[5,6,1,"","CTRL_RIGHT"],[5,6,1,"","CUT"],[5,6,1,"","D"],[5,6,1,"","DEL"],[5,6,1,"","DIGIT_0"],[5,6,1,"","DIGIT_1"],[5,6,1,"","DIGIT_2"],[5,6,1,"","DIGIT_3"],[5,6,1,"","DIGIT_4"],[5,6,1,"","DIGIT_5"],[5,6,1,"","DIGIT_6"],[5,6,1,"","DIGIT_7"],[5,6,1,"","DIGIT_8"],[5,6,1,"","DIGIT_9"],[5,6,1,"","DPAD_CENTER"],[5,6,1,"","DPAD_DOWN"],[5,6,1,"","DPAD_DOWN_LEFT"],[5,6,1,"","DPAD_DOWN_RIGHT"],[5,6,1,"","DPAD_LEFT"],[5,6,1,"","DPAD_RIGHT"],[5,6,1,"","DPAD_UP"],[5,6,1,"","DPAD_UP_LEFT"],[5,6,1,"","DPAD_UP_RIGHT"],[5,6,1,"","DVR"],[5,6,1,"","E"],[5,6,1,"","EISU"],[5,6,1,"","ENDCALL"],[5,6,1,"","ENTER"],[5,6,1,"","ENVELOPE"],[5,6,1,"","EQUALS"],[5,6,1,"","ESCAPE"],[5,6,1,"","EXPLORER"],[5,6,1,"","F"],[5,6,1,"","F1"],[5,6,1,"","F10"],[5,6,1,"","F11"],[5,6,1,"","F12"],[5,6,1,"","F2"],[5,6,1,"","F3"],[5,6,1,"","F4"],[5,6,1,"","F5"],[5,6,1,"","F6"],[5,6,1,"","F7"],[5,6,1,"","F8"],[5,6,1,"","F9"],[5,6,1,"","FOCUS"],[5,6,1,"","FORWARD"],[5,6,1,"","FORWARD_DEL"],[5,6,1,"","FUNCTION"],[5,6,1,"","G"],[5,6,1,"","GRAVE"],[5,6,1,"","GUIDE"],[5,6,1,"","H"],[5,6,1,"","HEADSETHOOK"],[5,6,1,"","HELP"],[5,6,1,"","HENKAN"],[5,6,1,"","HOME"],[5,6,1,"","I"],[5,6,1,"","INFO"],[5,6,1,"","INSERT"],[5,6,1,"","J"],[5,6,1,"","K"],[5,6,1,"","KANA"],[5,6,1,"","KATAKANA_HIRAGANA"],[5,6,1,"","KEYCODE_ZOOM_IN"],[5,6,1,"","KEYCODE_ZOOM_OUT"],[5,6,1,"","KEY_11"],[5,6,1,"","KEY_12"],[5,6,1,"","L"],[5,6,1,"","LANGUAGE_SWITCH"],[5,6,1,"","LAST_CHANNEL"],[5,6,1,"","LEFT_BRACKET"],[5,6,1,"","M"],[5,6,1,"","MANNER_MODE"],[5,6,1,"","MEDIA_AUDIO_TRACK"],[5,6,1,"","MEDIA_CLOSE"],[5,6,1,"","MEDIA_EJECT"],[5,6,1,"","MEDIA_FAST_FORWARD"],[5,6,1,"","MEDIA_NEXT"],[5,6,1,"","MEDIA_PAUSE"],[5,6,1,"","MEDIA_PLAY"],[5,6,1,"","MEDIA_PLAY_PAUSE"],[5,6,1,"","MEDIA_PREVIOUS"],[5,6,1,"","MEDIA_RECORD"],[5,6,1,"","MEDIA_REWIND"],[5,6,1,"","MEDIA_SKIP_BACKWARD"],[5,6,1,"","MEDIA_SKIP_FORWARD"],[5,6,1,"","MEDIA_STEP_BACKWARD"],[5,6,1,"","MEDIA_STEP_FORWARD"],[5,6,1,"","MEDIA_STOP"],[5,6,1,"","MEDIA_TOP_MENU"],[5,6,1,"","MENU"],[5,6,1,"","META_LEFT"],[5,6,1,"","META_RIGHT"],[5,6,1,"","MINUS"],[5,6,1,"","MODE_3D"],[5,6,1,"","MOVE_END"],[5,6,1,"","MOVE_HOME"],[5,6,1,"","MUHENKAN"],[5,6,1,"","MUSIC"],[5,6,1,"","MUTE"],[5,6,1,"","N"],[5,6,1,"","NAVIGATE_IN"],[5,6,1,"","NAVIGATE_NEXT"],[5,6,1,"","NAVIGATE_OUT"],[5,6,1,"","NAVIGATE_PREVIOUS"],[5,6,1,"","NOTIFICATION"],[5,6,1,"","NUM"],[5,6,1,"","NUMPAD_0"],[5,6,1,"","NUMPAD_1"],[5,6,1,"","NUMPAD_2"],[5,6,1,"","NUMPAD_3"],[5,6,1,"","NUMPAD_4"],[5,6,1,"","NUMPAD_5"],[5,6,1,"","NUMPAD_6"],[5,6,1,"","NUMPAD_7"],[5,6,1,"","NUMPAD_8"],[5,6,1,"","NUMPAD_9"],[5,6,1,"","NUMPAD_ADD"],[5,6,1,"","NUMPAD_COMMA"],[5,6,1,"","NUMPAD_DIVIDE"],[5,6,1,"","NUMPAD_DOT"],[5,6,1,"","NUMPAD_ENTER"],[5,6,1,"","NUMPAD_EQUALS"],[5,6,1,"","NUMPAD_LEFT_PAREN"],[5,6,1,"","NUMPAD_MULTIPLY"],[5,6,1,"","NUMPAD_RIGHT_PAREN"],[5,6,1,"","NUMPAD_SUBTRACT"],[5,6,1,"","NUM_LOCK"],[5,6,1,"","O"],[5,6,1,"","P"],[5,6,1,"","PAGE_DOWN"],[5,6,1,"","PAGE_UP"],[5,6,1,"","PAIRING"],[5,6,1,"","PERIOD"],[5,6,1,"","PICTSYMBOLS"],[5,6,1,"","PLUS"],[5,6,1,"","POUND"],[5,6,1,"","POWER"],[5,6,1,"","PROG_BLUE"],[5,6,1,"","PROG_GREEN"],[5,6,1,"","PROG_RED"],[5,6,1,"","PROG_YELLOW"],[5,6,1,"","Q"],[5,6,1,"","R"],[5,6,1,"","RIGHT_BRACKET"],[5,6,1,"","RO"],[5,6,1,"","S"],[5,6,1,"","SCROLL_LOCK"],[5,6,1,"","SEARCH"],[5,6,1,"","SEMICOLON"],[5,6,1,"","SETTINGS"],[5,6,1,"","SHIFT_LEFT"],[5,6,1,"","SHIFT_RIGHT"],[5,6,1,"","SLASH"],[5,6,1,"","SLEEP"],[5,6,1,"","SOFT_LEFT"],[5,6,1,"","SOFT_RIGHT"],[5,6,1,"","SOFT_SLEEP"],[5,6,1,"","SPACE"],[5,6,1,"","STAR"],[5,6,1,"","STB_INPUT"],[5,6,1,"","STB_POWER"],[5,6,1,"","STEM_1"],[5,6,1,"","STEM_2"],[5,6,1,"","STEM_3"],[5,6,1,"","STEM_PRIMARY"],[5,6,1,"","SWITCH_CHARSET"],[5,6,1,"","SYM"],[5,6,1,"","SYSRQ"],[5,6,1,"","T"],[5,6,1,"","TAB"],[5,6,1,"","TV"],[5,6,1,"","TV_ANTENNA_CABLE"],[5,6,1,"","TV_AUDIO_DESCRIPTION"],[5,6,1,"","TV_AUDIO_DESCRIPTION_MIX_DOWN"],[5,6,1,"","TV_AUDIO_DESCRIPTION_MIX_UP"],[5,6,1,"","TV_CONTENTS_MENU"],[5,6,1,"","TV_DATA_SERVICE"],[5,6,1,"","TV_INPUT"],[5,6,1,"","TV_INPUT_COMPONENT_1"],[5,6,1,"","TV_INPUT_COMPONENT_2"],[5,6,1,"","TV_INPUT_COMPOSITE_1"],[5,6,1,"","TV_INPUT_COMPOSITE_2"],[5,6,1,"","TV_INPUT_HDMI_1"],[5,6,1,"","TV_INPUT_HDMI_2"],[5,6,1,"","TV_INPUT_HDMI_3"],[5,6,1,"","TV_INPUT_HDMI_4"],[5,6,1,"","TV_INPUT_VGA_1"],[5,6,1,"","TV_MEDIA_CONTEXT_MENU"],[5,6,1,"","TV_NETWORK"],[5,6,1,"","TV_NUMBER_ENTRY"],[5,6,1,"","TV_POWER"],[5,6,1,"","TV_RADIO_SERVICE"],[5,6,1,"","TV_SATELLITE"],[5,6,1,"","TV_SATELLITE_BS"],[5,6,1,"","TV_SATELLITE_CS"],[5,6,1,"","TV_SATELLITE_SERVICE"],[5,6,1,"","TV_TELETEXT"],[5,6,1,"","TV_TERRESTRIAL_ANALOG"],[5,6,1,"","TV_TERRESTRIAL_DIGITAL"],[5,6,1,"","TV_TIMER_PROGRAMMING"],[5,6,1,"","TV_ZOOM_MODE"],[5,6,1,"","U"],[5,6,1,"","UNKNOWN"],[5,6,1,"","V"],[5,6,1,"","VOICE_ASSIST"],[5,6,1,"","VOLUME_DOWN"],[5,6,1,"","VOLUME_MUTE"],[5,6,1,"","VOLUME_UP"],[5,6,1,"","W"],[5,6,1,"","WAKEUP"],[5,6,1,"","WINDOW"],[5,6,1,"","X"],[5,6,1,"","Y"],[5,6,1,"","YEN"],[5,6,1,"","Z"],[5,6,1,"","ZENKAKU_HANKAKU"],[5,6,1,"","confirm_buttons"],[5,6,1,"","gamepad_buttons"],[5,4,1,"","is_confirm_key"],[5,4,1,"","is_gamepad_button"],[5,4,1,"","is_media_key"],[5,4,1,"","is_system_key"],[5,4,1,"","is_wake_key"],[5,6,1,"","media_buttons"],[5,6,1,"","system_buttons"],[5,6,1,"","wake_buttons"]],"appium.webdriver.extensions.android.network":[[5,3,1,"","NetSpeed"],[5,3,1,"","Network"]],"appium.webdriver.extensions.android.network.NetSpeed":[[5,6,1,"","EDGE"],[5,6,1,"","EVDO"],[5,6,1,"","FULL"],[5,6,1,"","GPRS"],[5,6,1,"","GSM"],[5,6,1,"","HSDPA"],[5,6,1,"","LTE"],[5,6,1,"","SCSD"],[5,6,1,"","UMTS"]],"appium.webdriver.extensions.android.network.Network":[[5,5,1,"","network_connection"],[5,4,1,"","set_network_connection"],[5,4,1,"","set_network_speed"],[5,4,1,"","toggle_wifi"]],"appium.webdriver.extensions.android.performance":[[5,3,1,"","Performance"]],"appium.webdriver.extensions.android.performance.Performance":[[5,4,1,"","get_performance_data"],[5,4,1,"","get_performance_data_types"]],"appium.webdriver.extensions.android.power":[[5,3,1,"","Power"]],"appium.webdriver.extensions.android.power.Power":[[5,6,1,"","AC_OFF"],[5,6,1,"","AC_ON"],[5,4,1,"","set_power_ac"],[5,4,1,"","set_power_capacity"]],"appium.webdriver.extensions.android.sms":[[5,3,1,"","Sms"]],"appium.webdriver.extensions.android.sms.Sms":[[5,4,1,"","send_sms"]],"appium.webdriver.extensions.android.system_bars":[[5,3,1,"","SystemBars"]],"appium.webdriver.extensions.android.system_bars.SystemBars":[[5,4,1,"","get_system_bars"]],"appium.webdriver.extensions.applications":[[4,3,1,"","Applications"]],"appium.webdriver.extensions.applications.Applications":[[4,4,1,"","activate_app"],[4,4,1,"","app_strings"],[4,4,1,"","background_app"],[4,4,1,"","close_app"],[4,4,1,"","install_app"],[4,4,1,"","is_app_installed"],[4,4,1,"","launch_app"],[4,4,1,"","query_app_state"],[4,4,1,"","remove_app"],[4,4,1,"","reset"],[4,4,1,"","terminate_app"]],"appium.webdriver.extensions.clipboard":[[4,3,1,"","Clipboard"]],"appium.webdriver.extensions.clipboard.Clipboard":[[4,4,1,"","get_clipboard"],[4,4,1,"","get_clipboard_text"],[4,4,1,"","set_clipboard"],[4,4,1,"","set_clipboard_text"]],"appium.webdriver.extensions.context":[[4,3,1,"","Context"]],"appium.webdriver.extensions.context.Context":[[4,5,1,"","context"],[4,5,1,"","contexts"],[4,5,1,"","current_context"]],"appium.webdriver.extensions.device_time":[[4,3,1,"","DeviceTime"]],"appium.webdriver.extensions.device_time.DeviceTime":[[4,5,1,"","device_time"],[4,4,1,"","get_device_time"]],"appium.webdriver.extensions.execute_driver":[[4,3,1,"","ExecuteDriver"]],"appium.webdriver.extensions.execute_driver.ExecuteDriver":[[4,4,1,"","execute_driver"]],"appium.webdriver.extensions.execute_mobile_command":[[4,3,1,"","ExecuteMobileCommand"]],"appium.webdriver.extensions.execute_mobile_command.ExecuteMobileCommand":[[4,5,1,"","battery_info"],[4,4,1,"","press_button"]],"appium.webdriver.extensions.hw_actions":[[4,3,1,"","HardwareActions"]],"appium.webdriver.extensions.hw_actions.HardwareActions":[[4,4,1,"","finger_print"],[4,4,1,"","is_locked"],[4,4,1,"","lock"],[4,4,1,"","shake"],[4,4,1,"","toggle_touch_id_enrollment"],[4,4,1,"","touch_id"],[4,4,1,"","unlock"]],"appium.webdriver.extensions.images_comparison":[[4,3,1,"","ImagesComparison"]],"appium.webdriver.extensions.images_comparison.ImagesComparison":[[4,4,1,"","find_image_occurrence"],[4,4,1,"","get_images_similarity"],[4,4,1,"","match_images_features"]],"appium.webdriver.extensions.ime":[[4,3,1,"","IME"]],"appium.webdriver.extensions.ime.IME":[[4,4,1,"","activate_ime_engine"],[4,5,1,"","active_ime_engine"],[4,5,1,"","available_ime_engines"],[4,4,1,"","deactivate_ime_engine"],[4,4,1,"","is_ime_active"]],"appium.webdriver.extensions.keyboard":[[4,3,1,"","Keyboard"]],"appium.webdriver.extensions.keyboard.Keyboard":[[4,4,1,"","hide_keyboard"],[4,4,1,"","is_keyboard_shown"],[4,4,1,"","keyevent"],[4,4,1,"","long_press_keycode"],[4,4,1,"","press_keycode"]],"appium.webdriver.extensions.location":[[4,3,1,"","Location"]],"appium.webdriver.extensions.location.Location":[[4,5,1,"","location"],[4,4,1,"","set_location"],[4,4,1,"","toggle_location_services"]],"appium.webdriver.extensions.log_event":[[4,3,1,"","LogEvent"]],"appium.webdriver.extensions.log_event.LogEvent":[[4,4,1,"","get_events"],[4,4,1,"","log_event"]],"appium.webdriver.extensions.remote_fs":[[4,3,1,"","RemoteFS"]],"appium.webdriver.extensions.remote_fs.RemoteFS":[[4,4,1,"","pull_file"],[4,4,1,"","pull_folder"],[4,4,1,"","push_file"]],"appium.webdriver.extensions.screen_record":[[4,3,1,"","ScreenRecord"]],"appium.webdriver.extensions.screen_record.ScreenRecord":[[4,4,1,"","start_recording_screen"],[4,4,1,"","stop_recording_screen"]],"appium.webdriver.extensions.search_context":[[6,3,1,"","AppiumSearchContext"],[6,3,1,"","AppiumWebElementSearchContext"],[6,0,0,"-","android"],[6,0,0,"-","base_search_context"],[6,0,0,"-","custom"],[6,0,0,"-","ios"],[6,0,0,"-","mobile"],[6,0,0,"-","windows"]],"appium.webdriver.extensions.search_context.android":[[6,3,1,"","AndroidSearchContext"]],"appium.webdriver.extensions.search_context.android.AndroidSearchContext":[[6,4,1,"","find_element_by_android_data_matcher"],[6,4,1,"","find_element_by_android_uiautomator"],[6,4,1,"","find_element_by_android_view_matcher"],[6,4,1,"","find_element_by_android_viewtag"],[6,4,1,"","find_elements_by_android_data_matcher"],[6,4,1,"","find_elements_by_android_uiautomator"],[6,4,1,"","find_elements_by_android_viewtag"]],"appium.webdriver.extensions.search_context.base_search_context":[[6,3,1,"","BaseSearchContext"]],"appium.webdriver.extensions.search_context.base_search_context.BaseSearchContext":[[6,4,1,"","find_element"],[6,4,1,"","find_elements"]],"appium.webdriver.extensions.search_context.custom":[[6,3,1,"","CustomSearchContext"]],"appium.webdriver.extensions.search_context.custom.CustomSearchContext":[[6,4,1,"","find_element_by_custom"],[6,4,1,"","find_elements_by_custom"]],"appium.webdriver.extensions.search_context.ios":[[6,3,1,"","iOSSearchContext"]],"appium.webdriver.extensions.search_context.ios.iOSSearchContext":[[6,4,1,"","find_element_by_ios_class_chain"],[6,4,1,"","find_element_by_ios_predicate"],[6,4,1,"","find_element_by_ios_uiautomation"],[6,4,1,"","find_elements_by_ios_class_chain"],[6,4,1,"","find_elements_by_ios_predicate"],[6,4,1,"","find_elements_by_ios_uiautomation"]],"appium.webdriver.extensions.search_context.mobile":[[6,3,1,"","MobileSearchContext"]],"appium.webdriver.extensions.search_context.mobile.MobileSearchContext":[[6,4,1,"","find_element_by_accessibility_id"],[6,4,1,"","find_element_by_image"],[6,4,1,"","find_elements_by_accessibility_id"],[6,4,1,"","find_elements_by_image"]],"appium.webdriver.extensions.search_context.windows":[[6,3,1,"","WindowsSearchContext"]],"appium.webdriver.extensions.search_context.windows.WindowsSearchContext":[[6,4,1,"","find_element_by_windows_uiautomation"],[6,4,1,"","find_elements_by_windows_uiautomation"]],"appium.webdriver.extensions.session":[[4,3,1,"","Session"]],"appium.webdriver.extensions.session.Session":[[4,5,1,"","all_sessions"],[4,5,1,"","events"],[4,5,1,"","session"]],"appium.webdriver.extensions.settings":[[4,3,1,"","Settings"]],"appium.webdriver.extensions.settings.Settings":[[4,4,1,"","get_settings"],[4,4,1,"","update_settings"]],"appium.webdriver.mobilecommand":[[2,3,1,"","MobileCommand"]],"appium.webdriver.mobilecommand.MobileCommand":[[2,6,1,"","ACTIVATE_APP"],[2,6,1,"","ACTIVATE_IME_ENGINE"],[2,6,1,"","BACKGROUND"],[2,6,1,"","CLEAR"],[2,6,1,"","CLOSE_APP"],[2,6,1,"","COMPARE_IMAGES"],[2,6,1,"","CONTEXTS"],[2,6,1,"","DEACTIVATE_IME_ENGINE"],[2,6,1,"","END_TEST_COVERAGE"],[2,6,1,"","EXECUTE_DRIVER"],[2,6,1,"","FINGER_PRINT"],[2,6,1,"","GET_ACTIVE_IME_ENGINE"],[2,6,1,"","GET_ALL_SESSIONS"],[2,6,1,"","GET_APP_STRINGS"],[2,6,1,"","GET_AVAILABLE_IME_ENGINES"],[2,6,1,"","GET_AVAILABLE_LOG_TYPES"],[2,6,1,"","GET_CLIPBOARD"],[2,6,1,"","GET_CURRENT_ACTIVITY"],[2,6,1,"","GET_CURRENT_CONTEXT"],[2,6,1,"","GET_CURRENT_PACKAGE"],[2,6,1,"","GET_DEVICE_TIME_GET"],[2,6,1,"","GET_DEVICE_TIME_POST"],[2,6,1,"","GET_DISPLAY_DENSITY"],[2,6,1,"","GET_EVENTS"],[2,6,1,"","GET_LOCATION"],[2,6,1,"","GET_LOG"],[2,6,1,"","GET_NETWORK_CONNECTION"],[2,6,1,"","GET_PERFORMANCE_DATA"],[2,6,1,"","GET_PERFORMANCE_DATA_TYPES"],[2,6,1,"","GET_SESSION"],[2,6,1,"","GET_SETTINGS"],[2,6,1,"","GET_SYSTEM_BARS"],[2,6,1,"","HIDE_KEYBOARD"],[2,6,1,"","INSTALL_APP"],[2,6,1,"","IS_APP_INSTALLED"],[2,6,1,"","IS_IME_ACTIVE"],[2,6,1,"","IS_KEYBOARD_SHOWN"],[2,6,1,"","IS_LOCKED"],[2,6,1,"","KEY_EVENT"],[2,6,1,"","LAUNCH_APP"],[2,6,1,"","LOCATION_IN_VIEW"],[2,6,1,"","LOCK"],[2,6,1,"","LOG_EVENT"],[2,6,1,"","LONG_PRESS_KEYCODE"],[2,6,1,"","MAKE_GSM_CALL"],[2,6,1,"","MULTI_ACTION"],[2,6,1,"","OPEN_NOTIFICATIONS"],[2,6,1,"","PRESS_KEYCODE"],[2,6,1,"","PULL_FILE"],[2,6,1,"","PULL_FOLDER"],[2,6,1,"","PUSH_FILE"],[2,6,1,"","QUERY_APP_STATE"],[2,6,1,"","REMOVE_APP"],[2,6,1,"","REPLACE_KEYS"],[2,6,1,"","RESET"],[2,6,1,"","SEND_SMS"],[2,6,1,"","SET_CLIPBOARD"],[2,6,1,"","SET_GSM_SIGNAL"],[2,6,1,"","SET_GSM_VOICE"],[2,6,1,"","SET_IMMEDIATE_VALUE"],[2,6,1,"","SET_LOCATION"],[2,6,1,"","SET_NETWORK_CONNECTION"],[2,6,1,"","SET_NETWORK_SPEED"],[2,6,1,"","SET_POWER_AC"],[2,6,1,"","SET_POWER_CAPACITY"],[2,6,1,"","SHAKE"],[2,6,1,"","START_ACTIVITY"],[2,6,1,"","START_RECORDING_SCREEN"],[2,6,1,"","STOP_RECORDING_SCREEN"],[2,6,1,"","SWITCH_TO_CONTEXT"],[2,6,1,"","TERMINATE_APP"],[2,6,1,"","TOGGLE_LOCATION_SERVICES"],[2,6,1,"","TOGGLE_TOUCH_ID_ENROLLMENT"],[2,6,1,"","TOGGLE_WIFI"],[2,6,1,"","TOUCH_ACTION"],[2,6,1,"","TOUCH_ID"],[2,6,1,"","UNLOCK"],[2,6,1,"","UPDATE_SETTINGS"]],"appium.webdriver.switch_to":[[2,3,1,"","MobileSwitchTo"]],"appium.webdriver.switch_to.MobileSwitchTo":[[2,4,1,"","context"]],"appium.webdriver.webdriver":[[2,3,1,"","ExtensionBase"],[2,3,1,"","WebDriver"]],"appium.webdriver.webdriver.ExtensionBase":[[2,4,1,"","add_command"],[2,4,1,"","execute"],[2,4,1,"","method_name"]],"appium.webdriver.webdriver.WebDriver":[[2,4,1,"","create_web_element"],[2,4,1,"","delete_extensions"],[2,4,1,"","find_element"],[2,4,1,"","find_elements"],[2,4,1,"","set_value"],[2,4,1,"","start_session"],[2,5,1,"","switch_to"]],"appium.webdriver.webelement":[[2,3,1,"","WebElement"]],"appium.webdriver.webelement.WebElement":[[2,4,1,"","clear"],[2,4,1,"","find_element"],[2,4,1,"","find_elements"],[2,4,1,"","get_attribute"],[2,4,1,"","is_displayed"],[2,5,1,"","location_in_view"],[2,4,1,"","send_keys"],[2,4,1,"","set_text"],[2,4,1,"","set_value"]],appium:[[1,0,0,"-","common"],[0,0,0,"-","version"],[2,0,0,"-","webdriver"]]},objnames:{"0":["py","module","Python module"],"1":["py","exception","Python exception"],"2":["py","function","Python function"],"3":["py","class","Python class"],"4":["py","method","Python method"],"5":["py","property","Python property"],"6":["py","attribute","Python attribute"]},objtypes:{"0":"py:module","1":"py:exception","2":"py:function","3":"py:class","4":"py:method","5":"py:property","6":"py:attribute"},terms:{"0":[1,2,3,4,5,6],"00":4,"1":[1,2,3,4,5,6],"10":[4,5],"100":[4,5],"1000":3,"10000":4,"101":5,"102":5,"103":5,"104":5,"105":5,"106":5,"107":5,"108":5,"109":5,"11":5,"110":5,"111":5,"112":5,"113":5,"114":5,"115":5,"116":5,"117":5,"118":5,"119":5,"12":[4,5],"120":[2,5],"121":5,"122":5,"123":5,"124":5,"125":5,"126":5,"127":[2,4,5,6],"128":5,"1280x720":4,"129":5,"13":5,"130":5,"131":5,"132":5,"133":5,"134":5,"135":5,"136":5,"137":5,"138":5,"139":5,"14":5,"140":5,"141":5,"142":5,"143":5,"144":5,"145":5,"146":5,"147":5,"148":5,"149":5,"15":[4,5],"150":5,"151":5,"152":5,"153":5,"154":5,"155":5,"156":5,"157":5,"158":5,"159":5,"16":[4,5],"160":5,"161":5,"162":5,"163":5,"164":5,"165":5,"166":[4,5],"167":5,"168":5,"169":5,"17":5,"170":5,"171":5,"172":5,"173":5,"174":5,"175":5,"176":5,"177":5,"178":5,"179":5,"18":[4,5],"180":[4,5],"181":5,"182":5,"183":5,"184":5,"185":5,"186":5,"187":5,"188":5,"189":5,"19":5,"190":5,"191":5,"192":5,"193":5,"194":5,"195":5,"196":5,"197":5,"198":5,"199":5,"2":[1,2,4,5,6],"20":[4,5],"200":5,"20000m":4,"201":5,"202":5,"203":5,"204":5,"205":5,"206":5,"207":5,"208":5,"209":5,"21":5,"210":5,"211":5,"212":5,"213":5,"214":5,"215":5,"216":5,"217":5,"218":5,"219":5,"22":5,"220":5,"221":5,"222":5,"223":5,"224":5,"225":5,"226":5,"227":5,"228":5,"229":5,"23":5,"230":5,"231":5,"232":5,"233":5,"234":5,"235":5,"236":5,"237":5,"238":5,"239":5,"24":5,"240":5,"241":5,"242":5,"243":5,"244":5,"245":5,"246":5,"247":5,"248":5,"249":5,"25":5,"250":5,"251":5,"252":5,"253":5,"254":5,"255":5,"256":5,"257":5,"258":5,"259":5,"26":5,"260":5,"261":5,"262":5,"263":5,"264":[4,5],"265":5,"266":5,"267":5,"268":5,"269":5,"27":[4,5],"270":5,"271":5,"272":5,"273":5,"274":5,"275":5,"276":5,"277":5,"278":5,"28":5,"29":5,"2bfbhelper":4,"3":[2,4,5,6],"30":5,"31":5,"32":5,"33":5,"34":5,"35":5,"36":5,"37":5,"38":5,"39":5,"4":[2,4,5],"40":5,"400":4,"41":5,"42":5,"43":5,"44":5,"4444":[2,4,5,6],"45":5,"4567":5,"46":5,"47":5,"4723":2,"48":5,"49":5,"5":[4,5],"50":5,"500":4,"500m":4,"51":5,"52":5,"53":5,"54":5,"55":5,"555":5,"5551234567":5,"56":5,"57":5,"58":5,"59":5,"6":[2,4,5],"60":[4,5],"600":4,"60000":2,"60000m":4,"61":5,"62":5,"63":5,"64":[4,5],"65":5,"66":5,"67":5,"68":5,"69":5,"7":5,"70":5,"71":5,"72":5,"73":5,"74":5,"75":5,"76":5,"77":5,"78":5,"79":5,"8":5,"80":5,"81":5,"82":5,"83":5,"84":5,"85":5,"86":5,"8601":4,"87":5,"88":5,"89":5,"9":5,"90":[4,5],"91":5,"92":5,"93":5,"94":5,"95":5,"96":5,"97":5,"98":5,"99":5,"boolean":2,"break":5,"byte":4,"case":2,"catch":4,"class":[1,2,3,4,5,6],"const":5,"default":[2,4,5,6],"do":[2,4],"enum":[2,5],"float":[3,4],"function":[4,5],"int":[1,2,3,4,5],"long":4,"new":[2,4],"return":[1,2,3,4,5,6],"static":5,"switch":[1,2],"true":[2,4,5,6],"try":[2,4],"while":[2,4],A:[2,4,5,6],AT:5,By:[2,3,4],For:[2,4],If:[2,3,4,5,6],In:4,It:[4,5,6],No:4,Not:4,ON:5,On:4,One:4,Or:4,The:[2,3,4,5,6],Then:2,These:[4,5],To:1,a1:3,a2:3,about:[2,4],abov:5,ac:5,ac_off:5,ac_on:5,ac_stat:5,accept:[4,5],access:[3,6],accessibility_id:[3,6],achiev:4,action:[3,5],action_help:[0,2],actionhelp:[2,4],activ:[1,2,4],activate_app:[2,4],activate_ime_engin:[2,4],activateapp:2,activateimeengin:2,active_ime_engin:4,actual:[2,4],ad:[2,6],adapterview:6,add:[2,3],add_command:2,addit:4,address:2,advanc:4,after:[4,5],against:[2,4],agast:4,airplan:[2,5],airplane_mod:2,akaz:4,alia:[2,5],all:[2,4,5],all_network_on:2,all_sess:4,allow:4,allowtestpackag:4,along:[4,5],alreadi:[2,4],also:[3,4],alt_left:5,alt_right:5,altitud:4,alwai:[2,4],an:[2,4,5,6],android:[2,3,4],android_data_match:3,android_uiautom:3,android_view_match:3,android_viewtag:3,androiddevelop:6,androidkei:5,androidsearchcontext:6,androidx:6,ani:[1,2,4,5,6],anim:6,anoth:[4,5],api:[4,5],apostroph:5,app:[2,4,5],app_act:5,app_id:4,app_packag:5,app_path:4,app_str:4,app_switch:5,app_wait_act:5,app_wait_packag:5,appium_connect:[0,7],appium_servic:[0,7],appiumbi:[0,2],appiumconnect:2,appiumsearchcontext:[2,6],appiumservic:2,appiumserviceerror:2,appiumwebelementsearchcontext:[2,6],appl:3,appli:[2,4],applic:[0,2,5],applicationst:[0,4,7],ar:[2,4,5,6],arbitrari:[2,5],arg:[2,4,6],argument:[2,4,5,6],arrai:4,assign:2,assist:5,asynchron:4,attempt:[4,5],attribut:[1,2],audioinput:4,authent:4,autom:5,automat:[2,4],automation_nam:2,avail:[2,4,5],available_ime_engin:4,avc:4,avfound:4,avr_input:5,avr_pow:5,b:5,back:5,background:[2,4],background_app:4,backslash:5,bar:[5,6],base64:4,base64_full_imag:4,base64_image1:4,base64_image2:4,base64_partial_imag:4,base64data:4,base:[1,2,3,4,5,6],base_search_context:[2,4],baseopt:[4,5,6],basesearchcontext:6,basic:6,batteri:[4,5],battery_info:4,been:[2,4],befor:[2,4],begin:[3,5],being:[2,4],belong:5,below:2,best:4,beta:4,better:4,between:[4,5],big:4,binari:4,bit:4,bitmask:5,bitrat:4,blob:[2,4,5],block:[4,5],bodi:2,boo:4,bookmark:5,bool:[2,4,5],both:4,bound:[4,5],brightness_down:5,brightness_up:5,brisk:4,brows:2,browser:2,browser_profil:[2,4,5,6],bruteforc:4,bruteforceham:4,bruteforcehamminglut:4,bruteforcel1:4,bruteforcesl2:4,bug:4,bugreport:4,build:2,bundle_id:4,button:[4,5],button_10:5,button_11:5,button_12:5,button_13:5,button_14:5,button_15:5,button_16:5,button_1:5,button_2:5,button_3:5,button_4:5,button_5:5,button_6:5,button_7:5,button_8:5,button_9:5,button_a:5,button_b:5,button_c:5,button_i:5,button_l1:5,button_l2:5,button_mod:5,button_nam:4,button_r1:5,button_r2:5,button_select:5,button_start:5,button_thumbl:5,button_thumbr:5,button_x:5,button_z:5,bytearrai:4,c:5,cach:4,calcul:[4,5],calendar:5,call:[2,4,5],callabl:2,camera:5,can:[1,2,4,5,6],cancel:5,cannot:4,cap:2,capabl:[2,4,6],capac:5,caps_lock:5,caption:5,captur:4,captureclick:4,capturecursor:4,card:4,categori:[4,5],cell:6,certain:4,chain:[3,6],chang:[4,5],channel_down:5,channel_up:5,charg:4,check:[2,4,5],check_respons:2,cl:1,class_chain_str:6,class_nam:2,classmethod:2,classnam:6,clear:[2,5],click:[4,5],client:[0,1,2,3],clipboard:[0,2],clipboard_content_typ:[0,7],clipboardcontenttyp:[2,4],close:4,close_app:[2,4],closeapp:2,cmd:4,code:[2,4,5],codec:4,collect:[4,5],com:[2,3,4,5,6],comma:5,command:[2,3,4],command_executor:[2,4,5,6],command_method:[0,7],commandmethod:2,common:[0,2,4,6,7],commun:2,compare_imag:2,compareimag:2,comparison:4,compat:4,complet:4,compli:4,compress:4,concept:4,conext:6,confirm_button:5,confus:4,conjunct:6,connect:[2,5],connection_typ:5,connectiontyp:[0,5,7],consid:2,consist:4,constant:[1,4],contact:5,contain:[2,4,5],content_typ:4,context:[0,1,2,6],context_nam:2,coordiat:3,coordin:[3,4],copi:[4,5],corner:3,correspond:[2,6],could:4,count:[3,4],coverag:5,cpu:[4,5],cpuinfo:5,creat:2,create_web_el:2,css:2,ctrl_left:5,ctrl_right:5,current:[1,2,4,5],current_act:5,current_context:4,current_packag:5,cursor:4,cursormatch:6,custom:[2,3,4],custom_method_nam:2,customfindmodul:6,customsearchcontext:6,customurlcommand:2,cut:5,d:5,data:[2,4,5],data_onli:2,data_read_timeout:5,data_typ:5,datamatch:3,date:4,datetim:4,dd:4,ddthh:4,deactiv:4,deactivate_ime_engin:[2,4],deactivateimeengin:2,decreas:4,def:2,defin:[2,6],del:5,delet:2,delete_extens:2,deni:5,densiti:5,depend:4,deploy:4,deprec:[3,6],describ:3,descript:[3,5],desir:[2,4],desired_cap:[2,4,5,6],destin:4,destination_el:4,destination_path:4,destinationel:4,detail:[2,3,4],detect:[2,4],detector:4,detectornam:4,develop:[3,4,6],devic:[4,5],device_tim:[0,2],deviceid:4,devicetim:[2,4],devnul:2,dict:[1,2,3,4,5,6],dictionari:[2,4,5],differ:2,digit_0:5,digit_1:5,digit_2:5,digit_3:5,digit_4:5,digit_5:5,digit_6:5,digit_7:5,digit_8:5,digit_9:5,dinam:2,direct_connect:2,disabl:4,discharg:4,displai:[2,4],distanc:4,doc:[2,3,4,5],document:[2,3],doe:[2,4],doesn:[1,2],dont_stop_app_on_reset:5,down:3,dpad_cent:5,dpad_down:5,dpad_down_left:5,dpad_down_right:5,dpad_left:5,dpad_right:5,dpad_up:5,dpad_up_left:5,dpad_up_right:5,dpi:5,draft:2,drag:4,drag_and_drop:4,driver:[1,2,3,4,5,6],due:4,dummi:6,dummy_arg:2,durat:[3,4],dure:5,dvr:5,e:[1,4,5,6],each:[4,6],ec:5,edg:[4,5],effect:4,eisu:5,either:4,el1:[3,4],el2:[3,4],el:3,element:[2,3,4,6],element_id:2,empti:4,emul:[4,5],en:[2,3,4,5],enabl:4,encod:4,end:[3,5],end_i:4,end_test_coverag:[2,5],end_x:4,endcal:5,endpoint:4,endtestcoverag:2,endtim:4,engin:4,enough:4,enrol:4,enter:5,entri:4,enumer:[2,5],env:2,envelop:5,environ:2,equal:[2,4,5],error:[2,4,6],errorhandl:[0,7],escap:5,espresso:6,evdo:5,event:[4,5],ever:6,exampl:[2,4],example_command:2,except:[0,2,4,7],execut:[2,4],execute_driv:[0,2],execute_mobile_command:[0,2],executedriv:[2,4],executemobilecommand:[2,4],exist:[1,2],expect:2,expir:4,explicitli:2,explor:5,extens:[0,2],extensionbas:2,extract:1,extract_const_attribut:1,f10:5,f11:5,f12:5,f1:5,f2:5,f3:5,f4172aa853cf:6,f4:5,f5:5,f6:5,f7:5,f8:5,f9:5,f:[4,5],fact:2,fail:4,fals:[2,4],fast:4,faster:4,featur:4,ffmpeg:4,field:4,file:[4,5],file_detector:[4,5,6],filefieldnam:4,files:4,filter:4,find:[1,2,4,6],find_el:[2,6],find_element_by_:2,find_element_by_accessibility_id:[2,6],find_element_by_android_data_match:6,find_element_by_android_uiautom:6,find_element_by_android_view_match:6,find_element_by_android_viewtag:6,find_element_by_custom:6,find_element_by_imag:6,find_element_by_ios_class_chain:6,find_element_by_ios_pred:6,find_element_by_ios_uiautom:6,find_element_by_windows_uiautom:6,find_elements_by_:2,find_elements_by_accessibility_id:6,find_elements_by_android_data_match:6,find_elements_by_android_uiautom:6,find_elements_by_android_viewtag:6,find_elements_by_custom:6,find_elements_by_imag:6,find_elements_by_ios_class_chain:6,find_elements_by_ios_pred:6,find_elements_by_ios_uiautom:6,find_elements_by_windows_uiautom:6,find_execut:2,find_image_occurr:[4,6],finger:[3,4],finger_id:4,finger_print:[2,4],fingerprint:2,finish:4,first:[2,4],fit:4,five:4,flag:[4,5],flannbas:4,flick:4,flip:4,flow:4,focu:[2,5],focus:5,folder:4,follow:[1,2,4],foo:[2,6],forc:[3,4],forcedrestart:4,forcefulli:2,forcerestart:4,forev:4,form:[4,6],format:[2,4,6],formfield:4,forward:5,forward_del:5,found:[2,4,6],fp:4,frame:4,from:[2,3,4,5],ftp:4,full:[2,4,5],fulli:6,funev:4,g:[1,4,5,6],gamepad:5,gamepad_button:5,gather:4,gener:[2,4],gestur:4,get:[1,2,4,5],get_active_ime_engin:2,get_all_sess:2,get_app_str:2,get_attribut:2,get_available_ime_engin:2,get_available_log_typ:2,get_clipboard:[2,4],get_clipboard_text:4,get_current_act:2,get_current_context:2,get_current_packag:2,get_device_tim:4,get_device_time_get:2,get_device_time_post:2,get_display_dens:[2,5],get_ev:[2,4],get_images_similar:4,get_loc:2,get_log:2,get_network_connect:2,get_performance_data:[2,5],get_performance_data_typ:[2,5],get_remote_connection_head:2,get_sess:2,get_set:[2,4],get_system_bar:[2,5],getactiveengin:2,getallsess:2,getappstr:2,getavailableimeengin:2,getavailablelogtyp:2,getclipboard:2,getcontext:2,getcurrentact:2,getcurrentcontext:2,getcurrentpackag:2,getdevicetimeget:2,getdevicetimepost:2,getdisplaydens:2,getloc:2,getlog:2,getlogev:2,getnetworkconnect:2,getperformancedata:2,getperformancedatatyp:2,getsess:2,getset:2,getsystembar:2,gftt:4,github:[2,4,5,6],give:2,given:[2,4,6],go:[4,6],good:[4,5],goodmatchesfactor:4,googl:2,gp:4,gpr:5,grant:4,grantpermiss:4,grave:5,great:5,gsm:[2,4],gsmcallact:5,gsmsignalstrength:5,gsmvoicest:5,guid:5,h:[4,5],ha:[2,4],hamcrest:6,happen:4,hardwareact:[2,4],hasentri:6,have:[2,6],head:2,header:4,headsethook:5,hei:5,height:[4,5],help:[4,5],helper:[0,7],henkan:5,here:2,hide:4,hide_keyboard:[2,4],hidekeyboard:2,high:4,highest:4,histogram:4,hold:[4,5],home:5,hood:6,host:2,how:4,hsdpa:5,html:[4,6],http:[2,3,4,5,6],hub:2,hw_action:[0,2],i:[4,5],id:[2,3,4,6],id_:[2,6],ignor:[2,4],ignore_proxi:2,illustr:4,im:[0,2],imag:[2,3,4,6],images_comparison:[0,2],imagescomparison:[2,4],img_path:6,imgproc:4,immedi:4,implicitli:6,improv:4,increas:4,index:[4,7],info:5,inform:[4,5],inherit:2,input:4,inputmethod:4,insert:5,instal:4,install_app:[2,4],installapp:2,instanc:[2,3,4,5],instead:[2,3],integ:5,intent:5,intent_act:5,intent_categori:5,intent_flag:5,interact:3,interest:5,interfac:2,interv:5,invalidswitchtotargetexcept:1,invok:6,io:[2,3,4],ios_class_chain:3,ios_pred:3,ios_uiautom:3,iossearchcontext:6,is_act:2,is_app_instal:[2,4],is_confirm_kei:5,is_displai:2,is_gamepad_button:5,is_ime_act:[2,4],is_keyboard_shown:[2,4],is_listen:2,is_lock:[2,4],is_media_kei:5,is_run:2,is_system_kei:5,is_wake_kei:5,isappinstal:2,isimeact:2,iskeyboardshown:2,islock:2,isn:4,iso:4,item:4,its:2,itself:[4,6],j:5,javadoc:6,javahamcrest:6,js:2,json:[2,6],json_wire_gestur:3,k:5,kana:5,katakana_hiragana:5,kaze:4,keep:4,keep_al:[2,4,5,6],keepdata:4,kei:[2,4,5],key_11:5,key_12:5,key_ev:2,key_nam:4,keyboard:[0,2],keycod:4,keycode_zoom_in:5,keycode_zoom_out:5,keyev:[2,4],keystor:4,keyword:[2,4,5],kill:4,kwarg:2,l:5,label:[4,6],languag:[3,4],language_switch:5,larger:4,last:3,last_channel:5,later:3,latin:4,latinim:4,latitud:4,launch_app:[2,4],launchapp:2,left:3,left_bracket:5,length:4,less:4,level:[1,4,5],lib:2,librari:[1,6],library_vers:1,libx264:4,lift:3,like:[2,5],limit:4,line:2,list:[1,2,3,4,5,6],list_devic:4,listen:2,load:4,local:4,localhost:2,locat:[0,2],location_in_view:2,locationinview:2,lock:[2,4],log:4,log_ev:[0,2],logcustomev:2,logev:[2,4],logger:[0,7],lol:5,long_press:3,long_press_keycod:[2,4],longitud:4,longpresskeycod:2,look:6,low:4,lower:4,lte:5,m:5,maco:4,made:4,main:2,main_script:2,make:[4,5],make_gsm_cal:[2,5],makegsmcal:2,mandatori:4,mani:4,manifest:4,manner_mod:5,map:[2,4],mark:4,master:[2,4,5],match:4,match_images_featur:4,matcher:6,matchfunc:4,max:5,maximum:[2,4],md:[2,4,5],mean:[2,4],media:[4,5],media_audio_track:5,media_button:5,media_clos:5,media_eject:5,media_fast_forward:5,media_next:5,media_paus:5,media_plai:5,media_play_paus:5,media_previ:5,media_record:5,media_rewind:5,media_skip_backward:5,media_skip_forward:5,media_step_backward:5,media_step_forward:5,media_stop:5,media_top_menu:5,medium:[4,6],megabit:4,member:5,memori:[4,5],menu:5,messag:[2,4,5],meta:4,meta_left:5,meta_right:5,metast:4,method:[2,4,5,6],method_nam:2,millisecond:3,minim:4,minu:5,minut:4,miss:4,mjpeg:4,mm:4,mobil:[2,4],mobilebi:[0,2],mobilecommand:[0,7],mobileerrorhandl:2,mobilesearchcontext:6,mobileswitchto:2,mobilewebel:2,mode:[2,5],mode_3d:5,moder:5,modul:7,momentj:4,more:[2,3,4],most:6,mous:4,move:[3,4],move_end:5,move_hom:5,move_to:3,movi:4,ms:[2,3,4],mser:4,msg:1,much:4,muhenkan:5,multi_act:[0,2],multiact:[2,3],multipart:4,music:5,must:[2,3,4,6],mute:5,my:5,mylabel:6,n:5,name:[2,4,5,6],nativ:[2,4,6],nativekei:[2,4],navig:5,navigate_in:5,navigate_next:5,navigate_out:5,navigate_previ:5,navigationbar:5,need:2,neg:2,netspe:5,network:[2,4],network_connect:5,no_connect:2,node:2,nodej:2,non:2,none:[1,2,3,4,5,6],none_or_unknown:5,nosuchcontextexcept:1,not_instal:2,not_run:2,note:6,notif:5,num:5,num_lock:5,number:[2,4,5],numer:4,numpad_0:5,numpad_1:5,numpad_2:5,numpad_3:5,numpad_4:5,numpad_5:5,numpad_6:5,numpad_7:5,numpad_8:5,numpad_9:5,numpad_add:5,numpad_comma:5,numpad_divid:5,numpad_dot:5,numpad_ent:5,numpad_equ:5,numpad_left_paren:5,numpad_multipli:5,numpad_right_paren:5,numpad_subtract:5,o:[4,5],objc:3,object:[2,3,5,6],occurr:4,off:[3,5],ondata:6,one:[3,4,5,6],onli:[2,3,4,5,6],onview:6,open:[4,5],open_notif:[2,5],opencv:4,opennotif:2,oper:[3,4,5],opt:[4,5],option:[1,2,3,4,5,6],optional_intent_argu:5,orb:4,order:[2,4],org:[4,6],origin:4,origin_el:4,originalel:4,other:[2,4],otherwis:4,out:5,output:[2,4],overlai:4,overrid:2,p:[2,4,5],packag:7,package_nam:5,page:7,page_down:5,page_up:5,pair:[2,5],paramet:[1,2,3,4,5,6],parent:[2,6],parsed_url:2,parseresult:2,part:[2,6],partial:4,particular:[3,4],pass:[2,4,6],password:4,patch:2,path:[2,4,5,6],paus:3,payload:4,per:4,percent:5,perform:[2,3,4],period:5,permiss:4,phone:5,phone_numb:5,photo:4,physic:4,pictsymbol:5,pipe:2,pix_fmt:4,pixel:4,pixelformat:4,place:4,plaintext:[2,4],platform:[2,4],platform_nam:2,platform_vers:2,pleas:[3,4],plu:5,plugin:6,png:4,point:[3,4],pointer:3,points1:4,points2:4,poll_url:2,poor:5,popen:2,port:2,portion:6,posit:4,possibl:[2,3,4,5],post:[2,4],pound:5,power:[2,4],predic:[3,6],predicate_str:6,prefer:2,prefix:6,present:[4,5],preset:4,press:[3,4],press_button:4,press_keycod:[2,4],presskeycod:2,pressur:3,prevent:6,previou:[2,3,4],previous:4,print:[1,4],privat:2,process:[2,4],profil:2,prog_blu:5,prog_green:5,prog_r:5,prog_yellow:5,properli:2,properti:[2,3,4,5],protocol:4,provid:[2,4,6],proxi:[2,4,5,6],pull:5,pull_fil:[2,4],pull_fold:[2,4],pullfil:2,pullfold:2,push_fil:[2,4],pushfil:2,put:[2,4],py_feature2d:4,py_match:4,py_tutori:4,pylint:6,python:[0,1,2,3],q:5,qualifi:6,qualiti:4,queri:4,query_app_st:[2,4],queryappst:2,quicktim:4,r:5,rais:[2,4,6],rang:[3,4],rate:4,ratio:4,read:[2,3,4,5],real:4,receiv:4,record:4,rect1:4,rect2:4,rect:4,recurs:6,refer:[4,6],region:4,regist:2,reinstal:4,rel:[2,3],releas:3,remain:[2,4],remot:[2,4,5,6],remote_connect:2,remote_f:[0,2],remote_server_addr:2,remoteconnect:2,remotef:[2,4],remotepath:4,remov:[2,4],remove_app:[2,4],removeapp:2,replac:[2,4],replace_kei:2,replacekei:2,repo:2,repres:4,request:[2,4],reset:[2,4,5],resolut:4,resolve_ip:2,respons:[2,4],restart:[2,4],result:4,retri:5,retriev:[2,4,5],right_bracket:5,ro:5,roam:5,rotat:4,run:[2,4,5],running_in_background:2,running_in_background_suspend:2,running_in_foreground:2,runtimeerror:2,s:[2,3,4,5,6],same:[2,4],satellit:4,save:4,scale:4,scan:4,score:4,screen:[1,3,4],screen_record:[0,2],screenrecord:[2,4],screenshot:6,script:4,script_typ:4,scroll:4,scroll_lock:5,scsd:5,sd:4,search:[5,6,7],search_context:[2,4],second:[4,5],see:[4,5],selector:6,selenium:[1,2,3,4,5,6],self:[2,3,4,5],semicolon:5,send:[2,3,4,5],send_kei:2,send_sm:[2,5],sender:5,sendsm:2,sent:[2,4],separ:4,sequenc:1,server:[2,3,4],servic:[2,4],session:[0,2],sessionid:2,set:[0,1,2,3,5],set_clipboard:[2,4],set_clipboard_text:4,set_gsm_sign:[2,5],set_gsm_voic:[2,5],set_immediate_valu:2,set_loc:[2,4],set_network_connect:[2,5],set_network_spe:[2,5],set_power_ac:[2,5],set_power_capac:[2,5],set_text:2,set_valu:2,setattr:2,setclipboard:2,setgsmsign:2,setgsmvoic:2,setimmediatevalu:2,setloc:2,setnetworkconnect:2,setnetworkspe:2,setpowerac:2,setpowercapac:2,setup_logg:1,shade:5,shake:[2,4],shift_left:5,shift_right:5,shortcut:[5,6],should:[2,4,5],shown:[4,5],sift:4,signal:5,similar:4,simpl:6,simul:[2,4],sinc:4,size:4,slash:5,sleep:5,slow:4,slower:4,sm:[2,4],so:[2,4],soft_left:5,soft_right:5,soft_sleep:5,softwar:4,some:[2,4],someth:4,sourc:[2,4],source_path:4,space:5,spec:[2,4],specifi:[2,3,4,5],speed:[4,5],speed_typ:5,ssz:4,stacktrac:1,star:5,start:[2,4,5],start_act:[2,5],start_i:4,start_recording_screen:[2,4],start_sess:2,start_x:4,startact:2,startrecordingscreen:2,starttim:4,state:[4,5],statu:5,statusbar:5,stb_input:5,stb_power:5,stderr:2,stdout:2,stem_1:5,stem_2:5,stem_3:5,stem_primari:5,still:4,stop:[2,4,5],stop_recording_screen:[2,4],stoprecordingscreen:2,store:[3,4],str:[1,2,3,4,5,6],strategi:[2,4],stream:4,strength:5,strict_ssl:2,string:[2,3,4,6],string_fil:4,subclass:2,submodul:7,subpackag:7,subprocess:2,success:4,successfulli:4,superfast:4,support:[4,5],swipe:4,switch_charset:5,switch_to:[0,7],switch_to_context:2,switchto:2,switchtocontext:2,sym:5,sysrq:5,system:[2,4,5],system_bar:[2,4],system_button:5,systembar:[2,5],t:[1,2,3,4,5],tab:5,tag:6,take:4,tap:[3,4],tapoutsid:4,target:[1,4,5],target_el:2,templat:4,template_match:4,termin:4,terminate_app:[2,4],terminateapp:2,test:[4,5,6],test_command:2,text:[2,4],than:4,thei:[2,4],them:[2,4],thi:[1,2,4,5,6],through:5,thrown:[1,4],time:[2,3,4,5],timelimit:4,timeout:[4,5],timeout_m:[2,4],timestamp:4,titl:6,todo:[4,5],toggl:[4,5],toggle_location_servic:[2,4],toggle_touch_id_enrol:[2,4],toggle_wifi:[2,5],togglelocationservic:2,toggletouchidenrol:2,togglewifi:2,too:4,top:3,topic:4,total:4,totalcount:4,touch:[3,4],touch_act:[0,2],touch_id:[2,4],touchact:[2,3],touchid:[2,4],trac:4,trace:2,traffic:5,train:6,transform:4,tri:2,trigger:5,truthi:2,tupl:[2,4],tutori:4,tv:5,tv_antenna_c:5,tv_audio_descript:5,tv_audio_description_mix_down:5,tv_audio_description_mix_up:5,tv_contents_menu:5,tv_data_servic:5,tv_input:5,tv_input_component_1:5,tv_input_component_2:5,tv_input_composite_1:5,tv_input_composite_2:5,tv_input_hdmi_1:5,tv_input_hdmi_2:5,tv_input_hdmi_3:5,tv_input_hdmi_4:5,tv_input_vga_1:5,tv_media_context_menu:5,tv_network:5,tv_number_entri:5,tv_power:5,tv_radio_servic:5,tv_satellit:5,tv_satellite_b:5,tv_satellite_c:5,tv_satellite_servic:5,tv_teletext:5,tv_terrestrial_analog:5,tv_terrestrial_digit:5,tv_timer_program:5,tv_zoom_mod:5,type:[1,2,3,4,5,6],typeerror:6,u:5,uia_str:6,uiautom:[3,6],uiautomator2:4,uikit:3,uitouch:3,ultrafast:4,umt:5,under:[4,6],uninstal:4,union:[2,3,4,5,6],unknown:5,unlimit:4,unlock:[2,4],unplug:4,unregist:5,unset:4,until:[2,4,5],up:4,update_set:[2,4],updateset:2,upgrad:4,upload:4,upon:3,url:2,us:[2,3,4,5,6],usag:[2,3,4,5,6],user:[2,4],usesdcard:4,usual:2,util:6,v:5,val1:1,val2:1,valid:6,valu:[1,2,3,4,5,6],variabl:2,vendor:4,versa:3,version:[1,7],veryfast:4,veryslow:4,vice:3,video:4,videofilt:4,videofp:4,videoqu:4,videos:4,videoscal:4,videotyp:4,view:[2,4,5,6],viewmatch:[3,6],viewtag:3,visibl:[2,5],visual:4,voic:5,voice_assist:5,volume_down:5,volume_mut:5,volume_up:5,w3c:[3,4],w:5,wa:[2,4],wai:1,wait:[2,3,4,5],wait_act:5,wake:5,wake_button:5,wakeup:5,want:[2,5],wd:2,web:[2,6],webdriv:[0,7],webdriverag:4,webdriveragentlib:4,webdriverexcept:4,webdriverio:4,webel:[0,3,4,6,7],webview_1:2,were:4,when:[1,2],where:[4,6],whether:[2,4],which:[2,4,5],whose:[2,4,5],width:[4,5],widthxheight:4,wifi:[2,5],wifi_onli:2,wiki:4,win:4,win_uiautom:6,window:[2,3,4,5],windows_ui_autom:3,windowssearchcontext:6,within:4,withtext:6,work:[4,6],write:[2,5],written:4,x:[2,3,4,5],xcuidevic:4,xcuielementtypeani:6,xcuielementtypebutton:6,xcuielementtypewindow:6,xcuitest:4,y:[2,3,4,5],yen:5,you:[1,2,4],your:[2,4],yourcustomcommand:2,yuv420p:4,yyyi:4,z:5,zenkaku_hankaku:5,zero:[2,4],zip:4},titles:["appium package","appium.common package","appium.webdriver package","appium.webdriver.common package","appium.webdriver.extensions package","appium.webdriver.extensions.android package","appium.webdriver.extensions.search_context package","Welcome to Appium python client\u2019s documentation!"],titleterms:{action_help:4,activ:5,android:[5,6],appium:[0,1,2,3,4,5,6,7],appium_connect:2,appium_servic:2,appiumbi:3,applic:4,applicationst:2,base_search_context:6,client:7,clipboard:4,clipboard_content_typ:2,command_method:2,common:[1,3,5],connectiontyp:2,content:[0,1,2,3,4,5,6,7],context:4,custom:6,device_tim:4,displai:5,document:7,errorhandl:2,except:1,execute_driv:4,execute_mobile_command:4,extens:[4,5,6],gsm:5,helper:1,hw_action:4,im:4,images_comparison:4,indic:7,io:6,keyboard:4,locat:4,log_ev:4,logger:1,mobil:6,mobilebi:3,mobilecommand:2,modul:[0,1,2,3,4,5,6],multi_act:3,nativekei:5,network:5,packag:[0,1,2,3,4,5,6],perform:5,power:5,python:7,remote_f:4,s:7,screen_record:4,search_context:6,session:4,set:4,sm:5,submodul:[0,1,2,3,4,5,6],subpackag:[0,2,4],switch_to:2,system_bar:5,tabl:7,touch_act:3,version:0,webdriv:[2,3,4,5,6],webel:2,welcom:7,window:6}})
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/_build/html/searchindex.js
searchindex.js
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define('underscore', factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, (function () { var current = global._; var exports = global._ = factory(); exports.noConflict = function () { global._ = current; return exports; }; }())); }(this, (function () { // Underscore.js 1.13.1 // https://underscorejs.org // (c) 2009-2021 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. // Current version. var VERSION = '1.13.1'; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self == 'object' && self.self === self && self || typeof global == 'object' && global.global === global && global || Function('return this')() || {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype; var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // Modern feature detection. var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined', supportsDataView = typeof DataView !== 'undefined'; // All **ECMAScript 5+** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeCreate = Object.create, nativeIsView = supportsArrayBuffer && ArrayBuffer.isView; // Create references to these builtin functions because we override them. var _isNaN = isNaN, _isFinite = isFinite; // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; // The largest integer that can be represented exactly. var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; // Some functions take a variable number of arguments, or a few expected // arguments at the beginning and then a variable number of values to operate // on. This helper accumulates all remaining arguments past the function’s // argument length (or an explicit `startIndex`), into an array that becomes // the last argument. Similar to ES6’s "rest parameter". function restArguments(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0), rest = Array(length), index = 0; for (; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); case 2: return func.call(this, arguments[0], arguments[1], rest); } var args = Array(startIndex + 1); for (index = 0; index < startIndex; index++) { args[index] = arguments[index]; } args[startIndex] = rest; return func.apply(this, args); }; } // Is a given variable an object? function isObject(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; } // Is a given value equal to null? function isNull(obj) { return obj === null; } // Is a given variable undefined? function isUndefined(obj) { return obj === void 0; } // Is a given value a boolean? function isBoolean(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; } // Is a given value a DOM element? function isElement(obj) { return !!(obj && obj.nodeType === 1); } // Internal function for creating a `toString`-based type tester. function tagTester(name) { var tag = '[object ' + name + ']'; return function(obj) { return toString.call(obj) === tag; }; } var isString = tagTester('String'); var isNumber = tagTester('Number'); var isDate = tagTester('Date'); var isRegExp = tagTester('RegExp'); var isError = tagTester('Error'); var isSymbol = tagTester('Symbol'); var isArrayBuffer = tagTester('ArrayBuffer'); var isFunction = tagTester('Function'); // Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old // v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236). var nodelist = root.document && root.document.childNodes; if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') { isFunction = function(obj) { return typeof obj == 'function' || false; }; } var isFunction$1 = isFunction; var hasObjectTag = tagTester('Object'); // In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`. // In IE 11, the most common among them, this problem also applies to // `Map`, `WeakMap` and `Set`. var hasStringTagBug = ( supportsDataView && hasObjectTag(new DataView(new ArrayBuffer(8))) ), isIE11 = (typeof Map !== 'undefined' && hasObjectTag(new Map)); var isDataView = tagTester('DataView'); // In IE 10 - Edge 13, we need a different heuristic // to determine whether an object is a `DataView`. function ie10IsDataView(obj) { return obj != null && isFunction$1(obj.getInt8) && isArrayBuffer(obj.buffer); } var isDataView$1 = (hasStringTagBug ? ie10IsDataView : isDataView); // Is a given value an array? // Delegates to ECMA5's native `Array.isArray`. var isArray = nativeIsArray || tagTester('Array'); // Internal function to check whether `key` is an own property name of `obj`. function has$1(obj, key) { return obj != null && hasOwnProperty.call(obj, key); } var isArguments = tagTester('Arguments'); // Define a fallback version of the method in browsers (ahem, IE < 9), where // there isn't any inspectable "Arguments" type. (function() { if (!isArguments(arguments)) { isArguments = function(obj) { return has$1(obj, 'callee'); }; } }()); var isArguments$1 = isArguments; // Is a given object a finite number? function isFinite$1(obj) { return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj)); } // Is the given value `NaN`? function isNaN$1(obj) { return isNumber(obj) && _isNaN(obj); } // Predicate-generating function. Often useful outside of Underscore. function constant(value) { return function() { return value; }; } // Common internal logic for `isArrayLike` and `isBufferLike`. function createSizePropertyCheck(getSizeProperty) { return function(collection) { var sizeProperty = getSizeProperty(collection); return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX; } } // Internal helper to generate a function to obtain property `key` from `obj`. function shallowProperty(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; } // Internal helper to obtain the `byteLength` property of an object. var getByteLength = shallowProperty('byteLength'); // Internal helper to determine whether we should spend extensive checks against // `ArrayBuffer` et al. var isBufferLike = createSizePropertyCheck(getByteLength); // Is a given value a typed array? var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/; function isTypedArray(obj) { // `ArrayBuffer.isView` is the most future-proof, so use it when available. // Otherwise, fall back on the above regular expression. return nativeIsView ? (nativeIsView(obj) && !isDataView$1(obj)) : isBufferLike(obj) && typedArrayPattern.test(toString.call(obj)); } var isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant(false); // Internal helper to obtain the `length` property of an object. var getLength = shallowProperty('length'); // Internal helper to create a simple lookup structure. // `collectNonEnumProps` used to depend on `_.contains`, but this led to // circular imports. `emulatedSet` is a one-off solution that only works for // arrays of strings. function emulatedSet(keys) { var hash = {}; for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true; return { contains: function(key) { return hash[key]; }, push: function(key) { hash[key] = true; return keys.push(key); } }; } // Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't // be iterated by `for key in ...` and thus missed. Extends `keys` in place if // needed. function collectNonEnumProps(obj, keys) { keys = emulatedSet(keys); var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; var proto = isFunction$1(constructor) && constructor.prototype || ObjProto; // Constructor is a special case. var prop = 'constructor'; if (has$1(obj, prop) && !keys.contains(prop)) keys.push(prop); while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) { keys.push(prop); } } } // Retrieve the names of an object's own properties. // Delegates to **ECMAScript 5**'s native `Object.keys`. function keys(obj) { if (!isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (has$1(obj, key)) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; } // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. function isEmpty(obj) { if (obj == null) return true; // Skip the more expensive `toString`-based type checks if `obj` has no // `.length`. var length = getLength(obj); if (typeof length == 'number' && ( isArray(obj) || isString(obj) || isArguments$1(obj) )) return length === 0; return getLength(keys(obj)) === 0; } // Returns whether an object has a given set of `key:value` pairs. function isMatch(object, attrs) { var _keys = keys(attrs), length = _keys.length; if (object == null) return !length; var obj = Object(object); for (var i = 0; i < length; i++) { var key = _keys[i]; if (attrs[key] !== obj[key] || !(key in obj)) return false; } return true; } // If Underscore is called as a function, it returns a wrapped object that can // be used OO-style. This wrapper holds altered versions of all functions added // through `_.mixin`. Wrapped objects may be chained. function _$1(obj) { if (obj instanceof _$1) return obj; if (!(this instanceof _$1)) return new _$1(obj); this._wrapped = obj; } _$1.VERSION = VERSION; // Extracts the result from a wrapped and chained object. _$1.prototype.value = function() { return this._wrapped; }; // Provide unwrapping proxies for some methods used in engine operations // such as arithmetic and JSON stringification. _$1.prototype.valueOf = _$1.prototype.toJSON = _$1.prototype.value; _$1.prototype.toString = function() { return String(this._wrapped); }; // Internal function to wrap or shallow-copy an ArrayBuffer, // typed array or DataView to a new view, reusing the buffer. function toBufferView(bufferSource) { return new Uint8Array( bufferSource.buffer || bufferSource, bufferSource.byteOffset || 0, getByteLength(bufferSource) ); } // We use this string twice, so give it a name for minification. var tagDataView = '[object DataView]'; // Internal recursive comparison function for `_.isEqual`. function eq(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // `null` or `undefined` only equal to itself (strict comparison). if (a == null || b == null) return false; // `NaN`s are equivalent, but non-reflexive. if (a !== a) return b !== b; // Exhaust primitive checks var type = typeof a; if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; return deepEq(a, b, aStack, bStack); } // Internal recursive comparison function for `_.isEqual`. function deepEq(a, b, aStack, bStack) { // Unwrap any wrapped objects. if (a instanceof _$1) a = a._wrapped; if (b instanceof _$1) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; // Work around a bug in IE 10 - Edge 13. if (hasStringTagBug && className == '[object Object]' && isDataView$1(a)) { if (!isDataView$1(b)) return false; className = tagDataView; } switch (className) { // These types are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN. if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; case '[object Symbol]': return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b); case '[object ArrayBuffer]': case tagDataView: // Coerce to typed array so we can fall through. return deepEq(toBufferView(a), toBufferView(b), aStack, bStack); } var areArrays = className === '[object Array]'; if (!areArrays && isTypedArray$1(a)) { var byteLength = getByteLength(a); if (byteLength !== getByteLength(b)) return false; if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true; areArrays = true; } if (!areArrays) { if (typeof a != 'object' || typeof b != 'object') return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(isFunction$1(aCtor) && aCtor instanceof aCtor && isFunction$1(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) { return false; } } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. // Initializing stack of traversed objects. // It's done here since we only need them for objects and arrays comparison. aStack = aStack || []; bStack = bStack || []; var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Recursively compare objects and arrays. if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. length = a.length; if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. while (length--) { if (!eq(a[length], b[length], aStack, bStack)) return false; } } else { // Deep compare objects. var _keys = keys(a), key; length = _keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (keys(b).length !== length) return false; while (length--) { // Deep compare each member key = _keys[length]; if (!(has$1(b, key) && eq(a[key], b[key], aStack, bStack))) return false; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return true; } // Perform a deep comparison to check if two objects are equal. function isEqual(a, b) { return eq(a, b); } // Retrieve all the enumerable property names of an object. function allKeys(obj) { if (!isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; } // Since the regular `Object.prototype.toString` type tests don't work for // some types in IE 11, we use a fingerprinting heuristic instead, based // on the methods. It's not great, but it's the best we got. // The fingerprint method lists are defined below. function ie11fingerprint(methods) { var length = getLength(methods); return function(obj) { if (obj == null) return false; // `Map`, `WeakMap` and `Set` have no enumerable keys. var keys = allKeys(obj); if (getLength(keys)) return false; for (var i = 0; i < length; i++) { if (!isFunction$1(obj[methods[i]])) return false; } // If we are testing against `WeakMap`, we need to ensure that // `obj` doesn't have a `forEach` method in order to distinguish // it from a regular `Map`. return methods !== weakMapMethods || !isFunction$1(obj[forEachName]); }; } // In the interest of compact minification, we write // each string in the fingerprints only once. var forEachName = 'forEach', hasName = 'has', commonInit = ['clear', 'delete'], mapTail = ['get', hasName, 'set']; // `Map`, `WeakMap` and `Set` each have slightly different // combinations of the above sublists. var mapMethods = commonInit.concat(forEachName, mapTail), weakMapMethods = commonInit.concat(mapTail), setMethods = ['add'].concat(commonInit, forEachName, hasName); var isMap = isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map'); var isWeakMap = isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap'); var isSet = isIE11 ? ie11fingerprint(setMethods) : tagTester('Set'); var isWeakSet = tagTester('WeakSet'); // Retrieve the values of an object's properties. function values(obj) { var _keys = keys(obj); var length = _keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[_keys[i]]; } return values; } // Convert an object into a list of `[key, value]` pairs. // The opposite of `_.object` with one argument. function pairs(obj) { var _keys = keys(obj); var length = _keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [_keys[i], obj[_keys[i]]]; } return pairs; } // Invert the keys and values of an object. The values must be serializable. function invert(obj) { var result = {}; var _keys = keys(obj); for (var i = 0, length = _keys.length; i < length; i++) { result[obj[_keys[i]]] = _keys[i]; } return result; } // Return a sorted list of the function names available on the object. function functions(obj) { var names = []; for (var key in obj) { if (isFunction$1(obj[key])) names.push(key); } return names.sort(); } // An internal function for creating assigner functions. function createAssigner(keysFunc, defaults) { return function(obj) { var length = arguments.length; if (defaults) obj = Object(obj); if (length < 2 || obj == null) return obj; for (var index = 1; index < length; index++) { var source = arguments[index], keys = keysFunc(source), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (!defaults || obj[key] === void 0) obj[key] = source[key]; } } return obj; }; } // Extend a given object with all the properties in passed-in object(s). var extend = createAssigner(allKeys); // Assigns a given object with all the own properties in the passed-in // object(s). // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) var extendOwn = createAssigner(keys); // Fill in a given object with default properties. var defaults = createAssigner(allKeys, true); // Create a naked function reference for surrogate-prototype-swapping. function ctor() { return function(){}; } // An internal function for creating a new object that inherits from another. function baseCreate(prototype) { if (!isObject(prototype)) return {}; if (nativeCreate) return nativeCreate(prototype); var Ctor = ctor(); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; } // Creates an object that inherits from the given prototype object. // If additional properties are provided then they will be added to the // created object. function create(prototype, props) { var result = baseCreate(prototype); if (props) extendOwn(result, props); return result; } // Create a (shallow-cloned) duplicate of an object. function clone(obj) { if (!isObject(obj)) return obj; return isArray(obj) ? obj.slice() : extend({}, obj); } // Invokes `interceptor` with the `obj` and then returns `obj`. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. function tap(obj, interceptor) { interceptor(obj); return obj; } // Normalize a (deep) property `path` to array. // Like `_.iteratee`, this function can be customized. function toPath$1(path) { return isArray(path) ? path : [path]; } _$1.toPath = toPath$1; // Internal wrapper for `_.toPath` to enable minification. // Similar to `cb` for `_.iteratee`. function toPath(path) { return _$1.toPath(path); } // Internal function to obtain a nested property in `obj` along `path`. function deepGet(obj, path) { var length = path.length; for (var i = 0; i < length; i++) { if (obj == null) return void 0; obj = obj[path[i]]; } return length ? obj : void 0; } // Get the value of the (deep) property on `path` from `object`. // If any property in `path` does not exist or if the value is // `undefined`, return `defaultValue` instead. // The `path` is normalized through `_.toPath`. function get(object, path, defaultValue) { var value = deepGet(object, toPath(path)); return isUndefined(value) ? defaultValue : value; } // Shortcut function for checking if an object has a given property directly on // itself (in other words, not on a prototype). Unlike the internal `has` // function, this public version can also traverse nested properties. function has(obj, path) { path = toPath(path); var length = path.length; for (var i = 0; i < length; i++) { var key = path[i]; if (!has$1(obj, key)) return false; obj = obj[key]; } return !!length; } // Keep the identity function around for default iteratees. function identity(value) { return value; } // Returns a predicate for checking whether an object has a given set of // `key:value` pairs. function matcher(attrs) { attrs = extendOwn({}, attrs); return function(obj) { return isMatch(obj, attrs); }; } // Creates a function that, when passed an object, will traverse that object’s // properties down the given `path`, specified as an array of keys or indices. function property(path) { path = toPath(path); return function(obj) { return deepGet(obj, path); }; } // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. function optimizeCb(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; // The 2-argument case is omitted because we’re not using it. case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; } // An internal function to generate callbacks that can be applied to each // element in a collection, returning the desired result — either `_.identity`, // an arbitrary callback, a property matcher, or a property accessor. function baseIteratee(value, context, argCount) { if (value == null) return identity; if (isFunction$1(value)) return optimizeCb(value, context, argCount); if (isObject(value) && !isArray(value)) return matcher(value); return property(value); } // External wrapper for our callback generator. Users may customize // `_.iteratee` if they want additional predicate/iteratee shorthand styles. // This abstraction hides the internal-only `argCount` argument. function iteratee(value, context) { return baseIteratee(value, context, Infinity); } _$1.iteratee = iteratee; // The function we call internally to generate a callback. It invokes // `_.iteratee` if overridden, otherwise `baseIteratee`. function cb(value, context, argCount) { if (_$1.iteratee !== iteratee) return _$1.iteratee(value, context); return baseIteratee(value, context, argCount); } // Returns the results of applying the `iteratee` to each element of `obj`. // In contrast to `_.map` it returns an object. function mapObject(obj, iteratee, context) { iteratee = cb(iteratee, context); var _keys = keys(obj), length = _keys.length, results = {}; for (var index = 0; index < length; index++) { var currentKey = _keys[index]; results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } return results; } // Predicate-generating function. Often useful outside of Underscore. function noop(){} // Generates a function for a given object that returns a given property. function propertyOf(obj) { if (obj == null) return noop; return function(path) { return get(obj, path); }; } // Run a function **n** times. function times(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = optimizeCb(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; } // Return a random integer between `min` and `max` (inclusive). function random(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); } // A (possibly faster) way to get the current timestamp as an integer. var now = Date.now || function() { return new Date().getTime(); }; // Internal helper to generate functions for escaping and unescaping strings // to/from HTML interpolation. function createEscaper(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped. var source = '(?:' + keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; } // Internal list of HTML entities for escaping. var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; // Function for escaping strings to HTML interpolation. var _escape = createEscaper(escapeMap); // Internal list of HTML entities for unescaping. var unescapeMap = invert(escapeMap); // Function for unescaping strings from HTML interpolation. var _unescape = createEscaper(unescapeMap); // By default, Underscore uses ERB-style template delimiters. Change the // following template settings to use alternative delimiters. var templateSettings = _$1.templateSettings = { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g, escape: /<%-([\s\S]+?)%>/g }; // When customizing `_.templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; function escapeChar(match) { return '\\' + escapes[match]; } // In order to prevent third-party code injection through // `_.templateSettings.variable`, we test it against the following regular // expression. It is intentionally a bit more liberal than just matching valid // identifiers, but still prevents possible loopholes through defaults or // destructuring assignment. var bareIdentifier = /^\s*(\w|\$)+\s*$/; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. function template(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = defaults({}, settings, _$1.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escapeRegExp, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offset. return match; }); source += "';\n"; var argument = settings.variable; if (argument) { // Insure against third-party code injection. (CVE-2021-23358) if (!bareIdentifier.test(argument)) throw new Error( 'variable is not a bare identifier: ' + argument ); } else { // If a variable is not specified, place data values in local scope. source = 'with(obj||{}){\n' + source + '}\n'; argument = 'obj'; } source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; var render; try { render = new Function(argument, '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _$1); }; // Provide the compiled source as a convenience for precompilation. template.source = 'function(' + argument + '){\n' + source + '}'; return template; } // Traverses the children of `obj` along `path`. If a child is a function, it // is invoked with its parent as context. Returns the value of the final // child, or `fallback` if any child is undefined. function result(obj, path, fallback) { path = toPath(path); var length = path.length; if (!length) { return isFunction$1(fallback) ? fallback.call(obj) : fallback; } for (var i = 0; i < length; i++) { var prop = obj == null ? void 0 : obj[path[i]]; if (prop === void 0) { prop = fallback; i = length; // Ensure we don't continue iterating. } obj = isFunction$1(prop) ? prop.call(obj) : prop; } return obj; } // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; function uniqueId(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; } // Start chaining a wrapped Underscore object. function chain(obj) { var instance = _$1(obj); instance._chain = true; return instance; } // Internal function to execute `sourceFunc` bound to `context` with optional // `args`. Determines whether to execute a function as a constructor or as a // normal function. function executeBound(sourceFunc, boundFunc, context, callingContext, args) { if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); var self = baseCreate(sourceFunc.prototype); var result = sourceFunc.apply(self, args); if (isObject(result)) return result; return self; } // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. `_` acts // as a placeholder by default, allowing any combination of arguments to be // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. var partial = restArguments(function(func, boundArgs) { var placeholder = partial.placeholder; var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; } while (position < arguments.length) args.push(arguments[position++]); return executeBound(func, bound, this, this, args); }; return bound; }); partial.placeholder = _$1; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). var bind = restArguments(function(func, context, args) { if (!isFunction$1(func)) throw new TypeError('Bind must be called on a function'); var bound = restArguments(function(callArgs) { return executeBound(func, bound, context, this, args.concat(callArgs)); }); return bound; }); // Internal helper for collection methods to determine whether a collection // should be iterated as an array or as an object. // Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 var isArrayLike = createSizePropertyCheck(getLength); // Internal implementation of a recursive `flatten` function. function flatten$1(input, depth, strict, output) { output = output || []; if (!depth && depth !== 0) { depth = Infinity; } else if (depth <= 0) { return output.concat(input); } var idx = output.length; for (var i = 0, length = getLength(input); i < length; i++) { var value = input[i]; if (isArrayLike(value) && (isArray(value) || isArguments$1(value))) { // Flatten current level of array or arguments object. if (depth > 1) { flatten$1(value, depth - 1, strict, output); idx = output.length; } else { var j = 0, len = value.length; while (j < len) output[idx++] = value[j++]; } } else if (!strict) { output[idx++] = value; } } return output; } // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. var bindAll = restArguments(function(obj, keys) { keys = flatten$1(keys, false, false); var index = keys.length; if (index < 1) throw new Error('bindAll must be passed function names'); while (index--) { var key = keys[index]; obj[key] = bind(obj[key], obj); } return obj; }); // Memoize an expensive function by storing its results. function memoize(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = '' + (hasher ? hasher.apply(this, arguments) : key); if (!has$1(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; } // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. var delay = restArguments(function(func, wait, args) { return setTimeout(function() { return func.apply(null, args); }, wait); }); // Defers a function, scheduling it to run after the current call stack has // cleared. var defer = partial(delay, _$1, 1); // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. function throttle(func, wait, options) { var timeout, context, args, result; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; var throttled = function() { var _now = now(); if (!previous && options.leading === false) previous = _now; var remaining = wait - (_now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = _now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; throttled.cancel = function() { clearTimeout(timeout); previous = 0; timeout = context = args = null; }; return throttled; } // When a sequence of calls of the returned function ends, the argument // function is triggered. The end of a sequence is defined by the `wait` // parameter. If `immediate` is passed, the argument function will be // triggered at the beginning of the sequence instead of at the end. function debounce(func, wait, immediate) { var timeout, previous, args, result, context; var later = function() { var passed = now() - previous; if (wait > passed) { timeout = setTimeout(later, wait - passed); } else { timeout = null; if (!immediate) result = func.apply(context, args); // This check is needed because `func` can recursively invoke `debounced`. if (!timeout) args = context = null; } }; var debounced = restArguments(function(_args) { context = this; args = _args; previous = now(); if (!timeout) { timeout = setTimeout(later, wait); if (immediate) result = func.apply(context, args); } return result; }); debounced.cancel = function() { clearTimeout(timeout); timeout = args = context = null; }; return debounced; } // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. function wrap(func, wrapper) { return partial(wrapper, func); } // Returns a negated version of the passed-in predicate. function negate(predicate) { return function() { return !predicate.apply(this, arguments); }; } // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. function compose() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; } // Returns a function that will only be executed on and after the Nth call. function after(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; } // Returns a function that will only be executed up to (but not including) the // Nth call. function before(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } if (times <= 1) func = null; return memo; }; } // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. var once = partial(before, 2); // Returns the first key on an object that passes a truth test. function findKey(obj, predicate, context) { predicate = cb(predicate, context); var _keys = keys(obj), key; for (var i = 0, length = _keys.length; i < length; i++) { key = _keys[i]; if (predicate(obj[key], key, obj)) return key; } } // Internal function to generate `_.findIndex` and `_.findLastIndex`. function createPredicateIndexFinder(dir) { return function(array, predicate, context) { predicate = cb(predicate, context); var length = getLength(array); var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { if (predicate(array[index], index, array)) return index; } return -1; }; } // Returns the first index on an array-like that passes a truth test. var findIndex = createPredicateIndexFinder(1); // Returns the last index on an array-like that passes a truth test. var findLastIndex = createPredicateIndexFinder(-1); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. function sortedIndex(array, obj, iteratee, context) { iteratee = cb(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = getLength(array); while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; } // Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions. function createIndexFinder(dir, predicateFind, sortedIndex) { return function(array, item, idx) { var i = 0, length = getLength(array); if (typeof idx == 'number') { if (dir > 0) { i = idx >= 0 ? idx : Math.max(idx + length, i); } else { length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; } } else if (sortedIndex && idx && length) { idx = sortedIndex(array, item); return array[idx] === item ? idx : -1; } if (item !== item) { idx = predicateFind(slice.call(array, i, length), isNaN$1); return idx >= 0 ? idx + i : -1; } for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { if (array[idx] === item) return idx; } return -1; }; } // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. var indexOf = createIndexFinder(1, findIndex, sortedIndex); // Return the position of the last occurrence of an item in an array, // or -1 if the item is not included in the array. var lastIndexOf = createIndexFinder(-1, findLastIndex); // Return the first value which passes a truth test. function find(obj, predicate, context) { var keyFinder = isArrayLike(obj) ? findIndex : findKey; var key = keyFinder(obj, predicate, context); if (key !== void 0 && key !== -1) return obj[key]; } // Convenience version of a common use case of `_.find`: getting the first // object containing specific `key:value` pairs. function findWhere(obj, attrs) { return find(obj, matcher(attrs)); } // The cornerstone for collection functions, an `each` // implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. function each(obj, iteratee, context) { iteratee = optimizeCb(iteratee, context); var i, length; if (isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { var _keys = keys(obj); for (i = 0, length = _keys.length; i < length; i++) { iteratee(obj[_keys[i]], _keys[i], obj); } } return obj; } // Return the results of applying the iteratee to each element. function map(obj, iteratee, context) { iteratee = cb(iteratee, context); var _keys = !isArrayLike(obj) && keys(obj), length = (_keys || obj).length, results = Array(length); for (var index = 0; index < length; index++) { var currentKey = _keys ? _keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; } // Internal helper to create a reducing function, iterating left or right. function createReduce(dir) { // Wrap code that reassigns argument variables in a separate function than // the one that accesses `arguments.length` to avoid a perf hit. (#1991) var reducer = function(obj, iteratee, memo, initial) { var _keys = !isArrayLike(obj) && keys(obj), length = (_keys || obj).length, index = dir > 0 ? 0 : length - 1; if (!initial) { memo = obj[_keys ? _keys[index] : index]; index += dir; } for (; index >= 0 && index < length; index += dir) { var currentKey = _keys ? _keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; return function(obj, iteratee, memo, context) { var initial = arguments.length >= 3; return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); }; } // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. var reduce = createReduce(1); // The right-associative version of reduce, also known as `foldr`. var reduceRight = createReduce(-1); // Return all the elements that pass a truth test. function filter(obj, predicate, context) { var results = []; predicate = cb(predicate, context); each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; } // Return all the elements for which a truth test fails. function reject(obj, predicate, context) { return filter(obj, negate(cb(predicate)), context); } // Determine whether all of the elements pass a truth test. function every(obj, predicate, context) { predicate = cb(predicate, context); var _keys = !isArrayLike(obj) && keys(obj), length = (_keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = _keys ? _keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; } // Determine if at least one element in the object passes a truth test. function some(obj, predicate, context) { predicate = cb(predicate, context); var _keys = !isArrayLike(obj) && keys(obj), length = (_keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = _keys ? _keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; } // Determine if the array or object contains a given item (using `===`). function contains(obj, item, fromIndex, guard) { if (!isArrayLike(obj)) obj = values(obj); if (typeof fromIndex != 'number' || guard) fromIndex = 0; return indexOf(obj, item, fromIndex) >= 0; } // Invoke a method (with arguments) on every item in a collection. var invoke = restArguments(function(obj, path, args) { var contextPath, func; if (isFunction$1(path)) { func = path; } else { path = toPath(path); contextPath = path.slice(0, -1); path = path[path.length - 1]; } return map(obj, function(context) { var method = func; if (!method) { if (contextPath && contextPath.length) { context = deepGet(context, contextPath); } if (context == null) return void 0; method = context[path]; } return method == null ? method : method.apply(context, args); }); }); // Convenience version of a common use case of `_.map`: fetching a property. function pluck(obj, key) { return map(obj, property(key)); } // Convenience version of a common use case of `_.filter`: selecting only // objects containing specific `key:value` pairs. function where(obj, attrs) { return filter(obj, matcher(attrs)); } // Return the maximum element (or element-based computation). function max(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) { obj = isArrayLike(obj) ? obj : values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value != null && value > result) { result = value; } } } else { iteratee = cb(iteratee, context); each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = v; lastComputed = computed; } }); } return result; } // Return the minimum element (or element-based computation). function min(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) { obj = isArrayLike(obj) ? obj : values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value != null && value < result) { result = value; } } } else { iteratee = cb(iteratee, context); each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = v; lastComputed = computed; } }); } return result; } // Sample **n** random values from a collection using the modern version of the // [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle). // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `_.map`. function sample(obj, n, guard) { if (n == null || guard) { if (!isArrayLike(obj)) obj = values(obj); return obj[random(obj.length - 1)]; } var sample = isArrayLike(obj) ? clone(obj) : values(obj); var length = getLength(sample); n = Math.max(Math.min(n, length), 0); var last = length - 1; for (var index = 0; index < n; index++) { var rand = random(index, last); var temp = sample[index]; sample[index] = sample[rand]; sample[rand] = temp; } return sample.slice(0, n); } // Shuffle a collection. function shuffle(obj) { return sample(obj, Infinity); } // Sort the object's values by a criterion produced by an iteratee. function sortBy(obj, iteratee, context) { var index = 0; iteratee = cb(iteratee, context); return pluck(map(obj, function(value, key, list) { return { value: value, index: index++, criteria: iteratee(value, key, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); } // An internal function used for aggregate "group by" operations. function group(behavior, partition) { return function(obj, iteratee, context) { var result = partition ? [[], []] : {}; iteratee = cb(iteratee, context); each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; } // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. var groupBy = group(function(result, value, key) { if (has$1(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `_.groupBy`, but for // when you know that your index values will be unique. var indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. var countBy = group(function(result, value, key) { if (has$1(result, key)) result[key]++; else result[key] = 1; }); // Split a collection into two arrays: one whose elements all pass the given // truth test, and one whose elements all do not pass the truth test. var partition = group(function(result, value, pass) { result[pass ? 0 : 1].push(value); }, true); // Safely create a real, live array from anything iterable. var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; function toArray(obj) { if (!obj) return []; if (isArray(obj)) return slice.call(obj); if (isString(obj)) { // Keep surrogate pair characters together. return obj.match(reStrSymbol); } if (isArrayLike(obj)) return map(obj, identity); return values(obj); } // Return the number of elements in a collection. function size(obj) { if (obj == null) return 0; return isArrayLike(obj) ? obj.length : keys(obj).length; } // Internal `_.pick` helper function to determine whether `key` is an enumerable // property name of `obj`. function keyInObj(value, key, obj) { return key in obj; } // Return a copy of the object only containing the allowed properties. var pick = restArguments(function(obj, keys) { var result = {}, iteratee = keys[0]; if (obj == null) return result; if (isFunction$1(iteratee)) { if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); keys = allKeys(obj); } else { iteratee = keyInObj; keys = flatten$1(keys, false, false); obj = Object(obj); } for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } return result; }); // Return a copy of the object without the disallowed properties. var omit = restArguments(function(obj, keys) { var iteratee = keys[0], context; if (isFunction$1(iteratee)) { iteratee = negate(iteratee); if (keys.length > 1) context = keys[1]; } else { keys = map(flatten$1(keys, false, false), String); iteratee = function(value, key) { return !contains(keys, key); }; } return pick(obj, iteratee, context); }); // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. function initial(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); } // Get the first element of an array. Passing **n** will return the first N // values in the array. The **guard** check allows it to work with `_.map`. function first(array, n, guard) { if (array == null || array.length < 1) return n == null || guard ? void 0 : []; if (n == null || guard) return array[0]; return initial(array, array.length - n); } // Returns everything but the first entry of the `array`. Especially useful on // the `arguments` object. Passing an **n** will return the rest N values in the // `array`. function rest(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); } // Get the last element of an array. Passing **n** will return the last N // values in the array. function last(array, n, guard) { if (array == null || array.length < 1) return n == null || guard ? void 0 : []; if (n == null || guard) return array[array.length - 1]; return rest(array, Math.max(0, array.length - n)); } // Trim out all falsy values from an array. function compact(array) { return filter(array, Boolean); } // Flatten out an array, either recursively (by default), or up to `depth`. // Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively. function flatten(array, depth) { return flatten$1(array, depth, false); } // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. var difference = restArguments(function(array, rest) { rest = flatten$1(rest, true, true); return filter(array, function(value){ return !contains(rest, value); }); }); // Return a version of the array that does not contain the specified value(s). var without = restArguments(function(array, otherArrays) { return difference(array, otherArrays); }); // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // The faster algorithm will not work with an iteratee if the iteratee // is not a one-to-one function, so providing an iteratee will disable // the faster algorithm. function uniq(array, isSorted, iteratee, context) { if (!isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = cb(iteratee, context); var result = []; var seen = []; for (var i = 0, length = getLength(array); i < length; i++) { var value = array[i], computed = iteratee ? iteratee(value, i, array) : value; if (isSorted && !iteratee) { if (!i || seen !== computed) result.push(value); seen = computed; } else if (iteratee) { if (!contains(seen, computed)) { seen.push(computed); result.push(value); } } else if (!contains(result, value)) { result.push(value); } } return result; } // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. var union = restArguments(function(arrays) { return uniq(flatten$1(arrays, true, true)); }); // Produce an array that contains every item shared between all the // passed-in arrays. function intersection(array) { var result = []; var argsLength = arguments.length; for (var i = 0, length = getLength(array); i < length; i++) { var item = array[i]; if (contains(result, item)) continue; var j; for (j = 1; j < argsLength; j++) { if (!contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; } // Complement of zip. Unzip accepts an array of arrays and groups // each array's elements on shared indices. function unzip(array) { var length = array && max(array, getLength).length || 0; var result = Array(length); for (var index = 0; index < length; index++) { result[index] = pluck(array, index); } return result; } // Zip together multiple lists into a single array -- elements that share // an index go together. var zip = restArguments(unzip); // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. Passing by pairs is the reverse of `_.pairs`. function object(list, values) { var result = {}; for (var i = 0, length = getLength(list); i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; } // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](https://docs.python.org/library/functions.html#range). function range(start, stop, step) { if (stop == null) { stop = start || 0; start = 0; } if (!step) { step = stop < start ? -1 : 1; } var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; } // Chunk a single array into multiple arrays, each containing `count` or fewer // items. function chunk(array, count) { if (count == null || count < 1) return []; var result = []; var i = 0, length = array.length; while (i < length) { result.push(slice.call(array, i, i += count)); } return result; } // Helper function to continue chaining intermediate results. function chainResult(instance, obj) { return instance._chain ? _$1(obj).chain() : obj; } // Add your own custom functions to the Underscore object. function mixin(obj) { each(functions(obj), function(name) { var func = _$1[name] = obj[name]; _$1.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return chainResult(this, func.apply(_$1, args)); }; }); return _$1; } // Add all mutator `Array` functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _$1.prototype[name] = function() { var obj = this._wrapped; if (obj != null) { method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) { delete obj[0]; } } return chainResult(this, obj); }; }); // Add all accessor `Array` functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _$1.prototype[name] = function() { var obj = this._wrapped; if (obj != null) obj = method.apply(obj, arguments); return chainResult(this, obj); }; }); // Named Exports var allExports = { __proto__: null, VERSION: VERSION, restArguments: restArguments, isObject: isObject, isNull: isNull, isUndefined: isUndefined, isBoolean: isBoolean, isElement: isElement, isString: isString, isNumber: isNumber, isDate: isDate, isRegExp: isRegExp, isError: isError, isSymbol: isSymbol, isArrayBuffer: isArrayBuffer, isDataView: isDataView$1, isArray: isArray, isFunction: isFunction$1, isArguments: isArguments$1, isFinite: isFinite$1, isNaN: isNaN$1, isTypedArray: isTypedArray$1, isEmpty: isEmpty, isMatch: isMatch, isEqual: isEqual, isMap: isMap, isWeakMap: isWeakMap, isSet: isSet, isWeakSet: isWeakSet, keys: keys, allKeys: allKeys, values: values, pairs: pairs, invert: invert, functions: functions, methods: functions, extend: extend, extendOwn: extendOwn, assign: extendOwn, defaults: defaults, create: create, clone: clone, tap: tap, get: get, has: has, mapObject: mapObject, identity: identity, constant: constant, noop: noop, toPath: toPath$1, property: property, propertyOf: propertyOf, matcher: matcher, matches: matcher, times: times, random: random, now: now, escape: _escape, unescape: _unescape, templateSettings: templateSettings, template: template, result: result, uniqueId: uniqueId, chain: chain, iteratee: iteratee, partial: partial, bind: bind, bindAll: bindAll, memoize: memoize, delay: delay, defer: defer, throttle: throttle, debounce: debounce, wrap: wrap, negate: negate, compose: compose, after: after, before: before, once: once, findKey: findKey, findIndex: findIndex, findLastIndex: findLastIndex, sortedIndex: sortedIndex, indexOf: indexOf, lastIndexOf: lastIndexOf, find: find, detect: find, findWhere: findWhere, each: each, forEach: each, map: map, collect: map, reduce: reduce, foldl: reduce, inject: reduce, reduceRight: reduceRight, foldr: reduceRight, filter: filter, select: filter, reject: reject, every: every, all: every, some: some, any: some, contains: contains, includes: contains, include: contains, invoke: invoke, pluck: pluck, where: where, max: max, min: min, shuffle: shuffle, sample: sample, sortBy: sortBy, groupBy: groupBy, indexBy: indexBy, countBy: countBy, partition: partition, toArray: toArray, size: size, pick: pick, omit: omit, first: first, head: first, take: first, initial: initial, last: last, rest: rest, tail: rest, drop: rest, compact: compact, flatten: flatten, without: without, uniq: uniq, unique: uniq, union: union, intersection: intersection, difference: difference, unzip: unzip, transpose: unzip, zip: zip, object: object, range: range, chunk: chunk, mixin: mixin, 'default': _$1 }; // Default Export // Add all of the Underscore functions to the wrapper object. var _ = mixin(allExports); // Legacy Node.js API. _._ = _; return _; }))); //# sourceMappingURL=underscore-umd.js.map
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/_build/html/_static/underscore-1.13.1.js
underscore-1.13.1.js
* select a different prefix for underscore */ $u = _.noConflict(); /** * make the code below compatible with browsers without * an installed firebug like debugger if (!window.console || !console.firebug) { var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {}; } */ /** * small helper function to urldecode strings * * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#Decoding_query_parameters_from_a_URL */ jQuery.urldecode = function(x) { if (!x) { return x } return decodeURIComponent(x.replace(/\+/g, ' ')); }; /** * small helper function to urlencode strings */ jQuery.urlencode = encodeURIComponent; /** * This function returns the parsed url parameters of the * current request. Multiple values per key are supported, * it will always return arrays of strings for the value parts. */ jQuery.getQueryParameters = function(s) { if (typeof s === 'undefined') s = document.location.search; var parts = s.substr(s.indexOf('?') + 1).split('&'); var result = {}; for (var i = 0; i < parts.length; i++) { var tmp = parts[i].split('=', 2); var key = jQuery.urldecode(tmp[0]); var value = jQuery.urldecode(tmp[1]); if (key in result) result[key].push(value); else result[key] = [value]; } return result; }; /** * highlight a given string on a jquery object by wrapping it in * span elements with the given class name. */ jQuery.fn.highlightText = function(text, className) { function highlight(node, addItems) { if (node.nodeType === 3) { var val = node.nodeValue; var pos = val.toLowerCase().indexOf(text); if (pos >= 0 && !jQuery(node.parentNode).hasClass(className) && !jQuery(node.parentNode).hasClass("nohighlight")) { var span; var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); if (isInSVG) { span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); } else { span = document.createElement("span"); span.className = className; } span.appendChild(document.createTextNode(val.substr(pos, text.length))); node.parentNode.insertBefore(span, node.parentNode.insertBefore( document.createTextNode(val.substr(pos + text.length)), node.nextSibling)); node.nodeValue = val.substr(0, pos); if (isInSVG) { var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); var bbox = node.parentElement.getBBox(); rect.x.baseVal.value = bbox.x; rect.y.baseVal.value = bbox.y; rect.width.baseVal.value = bbox.width; rect.height.baseVal.value = bbox.height; rect.setAttribute('class', className); addItems.push({ "parent": node.parentNode, "target": rect}); } } } else if (!jQuery(node).is("button, select, textarea")) { jQuery.each(node.childNodes, function() { highlight(this, addItems); }); } } var addItems = []; var result = this.each(function() { highlight(this, addItems); }); for (var i = 0; i < addItems.length; ++i) { jQuery(addItems[i].parent).before(addItems[i].target); } return result; }; /* * backward compatibility for jQuery.browser * This will be supported until firefox bug is fixed. */ if (!jQuery.browser) { jQuery.uaMatch = function(ua) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; jQuery.browser = {}; jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; } /** * Small JavaScript module for the documentation. */ var Documentation = { init : function() { this.fixFirefoxAnchorBug(); this.highlightSearchWords(); this.initIndexTable(); if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { this.initOnKeyListeners(); } }, /** * i18n support */ TRANSLATIONS : {}, PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, LOCALE : 'unknown', // gettext and ngettext don't access this so that the functions // can safely bound to a different name (_ = Documentation.gettext) gettext : function(string) { var translated = Documentation.TRANSLATIONS[string]; if (typeof translated === 'undefined') return string; return (typeof translated === 'string') ? translated : translated[0]; }, ngettext : function(singular, plural, n) { var translated = Documentation.TRANSLATIONS[singular]; if (typeof translated === 'undefined') return (n == 1) ? singular : plural; return translated[Documentation.PLURALEXPR(n)]; }, addTranslations : function(catalog) { for (var key in catalog.messages) this.TRANSLATIONS[key] = catalog.messages[key]; this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); this.LOCALE = catalog.locale; }, /** * add context elements like header anchor links */ addContextElements : function() { $('div[id] > :header:first').each(function() { $('<a class="headerlink">\u00B6</a>'). attr('href', '#' + this.id). attr('title', _('Permalink to this headline')). appendTo(this); }); $('dt[id]').each(function() { $('<a class="headerlink">\u00B6</a>'). attr('href', '#' + this.id). attr('title', _('Permalink to this definition')). appendTo(this); }); }, /** * workaround a firefox stupidity * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 */ fixFirefoxAnchorBug : function() { if (document.location.hash && $.browser.mozilla) window.setTimeout(function() { document.location.href += ''; }, 10); }, /** * highlight the search words provided in the url in the text */ highlightSearchWords : function() { var params = $.getQueryParameters(); var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; if (terms.length) { var body = $('div.body'); if (!body.length) { body = $('body'); } window.setTimeout(function() { $.each(terms, function() { body.highlightText(this.toLowerCase(), 'highlighted'); }); }, 10); $('<p class="highlight-link"><a href="javascript:Documentation.' + 'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>') .appendTo($('#searchbox')); } }, /** * init the domain index toggle buttons */ initIndexTable : function() { var togglers = $('img.toggler').click(function() { var src = $(this).attr('src'); var idnum = $(this).attr('id').substr(7); $('tr.cg-' + idnum).toggle(); if (src.substr(-9) === 'minus.png') $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); else $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); }).css('display', ''); if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { togglers.click(); } }, /** * helper function to hide the search marks again */ hideSearchWords : function() { $('#searchbox .highlight-link').fadeOut(300); $('span.highlighted').removeClass('highlighted'); }, /** * make the url absolute */ makeURL : function(relativeURL) { return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; }, /** * get the current relative url */ getCurrentURL : function() { var path = document.location.pathname; var parts = path.split(/\//); $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { if (this === '..') parts.pop(); }); var url = parts.join('/'); return path.substring(url.lastIndexOf('/') + 1, path.length - 1); }, initOnKeyListeners: function() { $(document).keydown(function(event) { var activeElementType = document.activeElement.tagName; // don't navigate when in search box, textarea, dropdown or button if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT' && activeElementType !== 'BUTTON' && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) { switch (event.keyCode) { case 37: // left var prevHref = $('link[rel="prev"]').prop('href'); if (prevHref) { window.location.href = prevHref; return false; } break; case 39: // right var nextHref = $('link[rel="next"]').prop('href'); if (nextHref) { window.location.href = nextHref; return false; } break; } } }); } }; // quick alias for translations _ = Documentation.gettext; $(document).ready(function() { Documentation.init(); });
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/_build/html/_static/doctools.js
doctools.js
var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"]; /* Non-minified version is copied as a separate JS file, is available */ /** * Porter Stemmer */ var Stemmer = function() { var step2list = { ational: 'ate', tional: 'tion', enci: 'ence', anci: 'ance', izer: 'ize', bli: 'ble', alli: 'al', entli: 'ent', eli: 'e', ousli: 'ous', ization: 'ize', ation: 'ate', ator: 'ate', alism: 'al', iveness: 'ive', fulness: 'ful', ousness: 'ous', aliti: 'al', iviti: 'ive', biliti: 'ble', logi: 'log' }; var step3list = { icate: 'ic', ative: '', alize: 'al', iciti: 'ic', ical: 'ic', ful: '', ness: '' }; var c = "[^aeiou]"; // consonant var v = "[aeiouy]"; // vowel var C = c + "[^aeiouy]*"; // consonant sequence var V = v + "[aeiou]*"; // vowel sequence var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0 var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1 var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1 var s_v = "^(" + C + ")?" + v; // vowel in stem this.stemWord = function (w) { var stem; var suffix; var firstch; var origword = w; if (w.length < 3) return w; var re; var re2; var re3; var re4; firstch = w.substr(0,1); if (firstch == "y") w = firstch.toUpperCase() + w.substr(1); // Step 1a re = /^(.+?)(ss|i)es$/; re2 = /^(.+?)([^s])s$/; if (re.test(w)) w = w.replace(re,"$1$2"); else if (re2.test(w)) w = w.replace(re2,"$1$2"); // Step 1b re = /^(.+?)eed$/; re2 = /^(.+?)(ed|ing)$/; if (re.test(w)) { var fp = re.exec(w); re = new RegExp(mgr0); if (re.test(fp[1])) { re = /.$/; w = w.replace(re,""); } } else if (re2.test(w)) { var fp = re2.exec(w); stem = fp[1]; re2 = new RegExp(s_v); if (re2.test(stem)) { w = stem; re2 = /(at|bl|iz)$/; re3 = new RegExp("([^aeiouylsz])\\1$"); re4 = new RegExp("^" + C + v + "[^aeiouwxy]$"); if (re2.test(w)) w = w + "e"; else if (re3.test(w)) { re = /.$/; w = w.replace(re,""); } else if (re4.test(w)) w = w + "e"; } } // Step 1c re = /^(.+?)y$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(s_v); if (re.test(stem)) w = stem + "i"; } // Step 2 re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; suffix = fp[2]; re = new RegExp(mgr0); if (re.test(stem)) w = stem + step2list[suffix]; } // Step 3 re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; suffix = fp[2]; re = new RegExp(mgr0); if (re.test(stem)) w = stem + step3list[suffix]; } // Step 4 re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; re2 = /^(.+?)(s|t)(ion)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(mgr1); if (re.test(stem)) w = stem; } else if (re2.test(w)) { var fp = re2.exec(w); stem = fp[1] + fp[2]; re2 = new RegExp(mgr1); if (re2.test(stem)) w = stem; } // Step 5 re = /^(.+?)e$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(mgr1); re2 = new RegExp(meq1); re3 = new RegExp("^" + C + v + "[^aeiouwxy]$"); if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) w = stem; } re = /ll$/; re2 = new RegExp(mgr1); if (re.test(w) && re2.test(w)) { re = /.$/; w = w.replace(re,""); } // and turn initial Y back to y if (firstch == "y") w = firstch.toLowerCase() + w.substr(1); return w; } } var splitChars = (function() { var result = {}; var singles = [96, 180, 187, 191, 215, 247, 749, 885, 903, 907, 909, 930, 1014, 1648, 1748, 1809, 2416, 2473, 2481, 2526, 2601, 2609, 2612, 2615, 2653, 2702, 2706, 2729, 2737, 2740, 2857, 2865, 2868, 2910, 2928, 2948, 2961, 2971, 2973, 3085, 3089, 3113, 3124, 3213, 3217, 3241, 3252, 3295, 3341, 3345, 3369, 3506, 3516, 3633, 3715, 3721, 3736, 3744, 3748, 3750, 3756, 3761, 3781, 3912, 4239, 4347, 4681, 4695, 4697, 4745, 4785, 4799, 4801, 4823, 4881, 5760, 5901, 5997, 6313, 7405, 8024, 8026, 8028, 8030, 8117, 8125, 8133, 8181, 8468, 8485, 8487, 8489, 8494, 8527, 11311, 11359, 11687, 11695, 11703, 11711, 11719, 11727, 11735, 12448, 12539, 43010, 43014, 43019, 43587, 43696, 43713, 64286, 64297, 64311, 64317, 64319, 64322, 64325, 65141]; var i, j, start, end; for (i = 0; i < singles.length; i++) { result[singles[i]] = true; } var ranges = [[0, 47], [58, 64], [91, 94], [123, 169], [171, 177], [182, 184], [706, 709], [722, 735], [741, 747], [751, 879], [888, 889], [894, 901], [1154, 1161], [1318, 1328], [1367, 1368], [1370, 1376], [1416, 1487], [1515, 1519], [1523, 1568], [1611, 1631], [1642, 1645], [1750, 1764], [1767, 1773], [1789, 1790], [1792, 1807], [1840, 1868], [1958, 1968], [1970, 1983], [2027, 2035], [2038, 2041], [2043, 2047], [2070, 2073], [2075, 2083], [2085, 2087], [2089, 2307], [2362, 2364], [2366, 2383], [2385, 2391], [2402, 2405], [2419, 2424], [2432, 2436], [2445, 2446], [2449, 2450], [2483, 2485], [2490, 2492], [2494, 2509], [2511, 2523], [2530, 2533], [2546, 2547], [2554, 2564], [2571, 2574], [2577, 2578], [2618, 2648], [2655, 2661], [2672, 2673], [2677, 2692], [2746, 2748], [2750, 2767], [2769, 2783], [2786, 2789], [2800, 2820], [2829, 2830], [2833, 2834], [2874, 2876], [2878, 2907], [2914, 2917], [2930, 2946], [2955, 2957], [2966, 2968], [2976, 2978], [2981, 2983], [2987, 2989], [3002, 3023], [3025, 3045], [3059, 3076], [3130, 3132], [3134, 3159], [3162, 3167], [3170, 3173], [3184, 3191], [3199, 3204], [3258, 3260], [3262, 3293], [3298, 3301], [3312, 3332], [3386, 3388], [3390, 3423], [3426, 3429], [3446, 3449], [3456, 3460], [3479, 3481], [3518, 3519], [3527, 3584], [3636, 3647], [3655, 3663], [3674, 3712], [3717, 3718], [3723, 3724], [3726, 3731], [3752, 3753], [3764, 3772], [3774, 3775], [3783, 3791], [3802, 3803], [3806, 3839], [3841, 3871], [3892, 3903], [3949, 3975], [3980, 4095], [4139, 4158], [4170, 4175], [4182, 4185], [4190, 4192], [4194, 4196], [4199, 4205], [4209, 4212], [4226, 4237], [4250, 4255], [4294, 4303], [4349, 4351], [4686, 4687], [4702, 4703], [4750, 4751], [4790, 4791], [4806, 4807], [4886, 4887], [4955, 4968], [4989, 4991], [5008, 5023], [5109, 5120], [5741, 5742], [5787, 5791], [5867, 5869], [5873, 5887], [5906, 5919], [5938, 5951], [5970, 5983], [6001, 6015], [6068, 6102], [6104, 6107], [6109, 6111], [6122, 6127], [6138, 6159], [6170, 6175], [6264, 6271], [6315, 6319], [6390, 6399], [6429, 6469], [6510, 6511], [6517, 6527], [6572, 6592], [6600, 6607], [6619, 6655], [6679, 6687], [6741, 6783], [6794, 6799], [6810, 6822], [6824, 6916], [6964, 6980], [6988, 6991], [7002, 7042], [7073, 7085], [7098, 7167], [7204, 7231], [7242, 7244], [7294, 7400], [7410, 7423], [7616, 7679], [7958, 7959], [7966, 7967], [8006, 8007], [8014, 8015], [8062, 8063], [8127, 8129], [8141, 8143], [8148, 8149], [8156, 8159], [8173, 8177], [8189, 8303], [8306, 8307], [8314, 8318], [8330, 8335], [8341, 8449], [8451, 8454], [8456, 8457], [8470, 8472], [8478, 8483], [8506, 8507], [8512, 8516], [8522, 8525], [8586, 9311], [9372, 9449], [9472, 10101], [10132, 11263], [11493, 11498], [11503, 11516], [11518, 11519], [11558, 11567], [11622, 11630], [11632, 11647], [11671, 11679], [11743, 11822], [11824, 12292], [12296, 12320], [12330, 12336], [12342, 12343], [12349, 12352], [12439, 12444], [12544, 12548], [12590, 12592], [12687, 12689], [12694, 12703], [12728, 12783], [12800, 12831], [12842, 12880], [12896, 12927], [12938, 12976], [12992, 13311], [19894, 19967], [40908, 40959], [42125, 42191], [42238, 42239], [42509, 42511], [42540, 42559], [42592, 42593], [42607, 42622], [42648, 42655], [42736, 42774], [42784, 42785], [42889, 42890], [42893, 43002], [43043, 43055], [43062, 43071], [43124, 43137], [43188, 43215], [43226, 43249], [43256, 43258], [43260, 43263], [43302, 43311], [43335, 43359], [43389, 43395], [43443, 43470], [43482, 43519], [43561, 43583], [43596, 43599], [43610, 43615], [43639, 43641], [43643, 43647], [43698, 43700], [43703, 43704], [43710, 43711], [43715, 43738], [43742, 43967], [44003, 44015], [44026, 44031], [55204, 55215], [55239, 55242], [55292, 55295], [57344, 63743], [64046, 64047], [64110, 64111], [64218, 64255], [64263, 64274], [64280, 64284], [64434, 64466], [64830, 64847], [64912, 64913], [64968, 65007], [65020, 65135], [65277, 65295], [65306, 65312], [65339, 65344], [65371, 65381], [65471, 65473], [65480, 65481], [65488, 65489], [65496, 65497]]; for (i = 0; i < ranges.length; i++) { start = ranges[i][0]; end = ranges[i][1]; for (j = start; j <= end; j++) { result[j] = true; } } return result; })(); function splitQuery(query) { var result = []; var start = -1; for (var i = 0; i < query.length; i++) { if (splitChars[query.charCodeAt(i)]) { if (start !== -1) { result.push(query.slice(start, i)); start = -1; } } else if (start === -1) { start = i; } } if (start !== -1) { result.push(query.slice(start)); } return result; }
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/_build/html/_static/language_data.js
language_data.js
!function(n,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define("underscore",r):(n="undefined"!=typeof globalThis?globalThis:n||self,function(){var t=n._,e=n._=r();e.noConflict=function(){return n._=t,e}}())}(this,(function(){ // Underscore.js 1.13.1 // https://underscorejs.org // (c) 2009-2021 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. var n="1.13.1",r="object"==typeof self&&self.self===self&&self||"object"==typeof global&&global.global===global&&global||Function("return this")()||{},t=Array.prototype,e=Object.prototype,u="undefined"!=typeof Symbol?Symbol.prototype:null,o=t.push,i=t.slice,a=e.toString,f=e.hasOwnProperty,c="undefined"!=typeof ArrayBuffer,l="undefined"!=typeof DataView,s=Array.isArray,p=Object.keys,v=Object.create,h=c&&ArrayBuffer.isView,y=isNaN,d=isFinite,g=!{toString:null}.propertyIsEnumerable("toString"),b=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],m=Math.pow(2,53)-1;function j(n,r){return r=null==r?n.length-1:+r,function(){for(var t=Math.max(arguments.length-r,0),e=Array(t),u=0;u<t;u++)e[u]=arguments[u+r];switch(r){case 0:return n.call(this,e);case 1:return n.call(this,arguments[0],e);case 2:return n.call(this,arguments[0],arguments[1],e)}var o=Array(r+1);for(u=0;u<r;u++)o[u]=arguments[u];return o[r]=e,n.apply(this,o)}}function _(n){var r=typeof n;return"function"===r||"object"===r&&!!n}function w(n){return void 0===n}function A(n){return!0===n||!1===n||"[object Boolean]"===a.call(n)}function x(n){var r="[object "+n+"]";return function(n){return a.call(n)===r}}var S=x("String"),O=x("Number"),M=x("Date"),E=x("RegExp"),B=x("Error"),N=x("Symbol"),I=x("ArrayBuffer"),T=x("Function"),k=r.document&&r.document.childNodes;"function"!=typeof/./&&"object"!=typeof Int8Array&&"function"!=typeof k&&(T=function(n){return"function"==typeof n||!1});var D=T,R=x("Object"),F=l&&R(new DataView(new ArrayBuffer(8))),V="undefined"!=typeof Map&&R(new Map),P=x("DataView");var q=F?function(n){return null!=n&&D(n.getInt8)&&I(n.buffer)}:P,U=s||x("Array");function W(n,r){return null!=n&&f.call(n,r)}var z=x("Arguments");!function(){z(arguments)||(z=function(n){return W(n,"callee")})}();var L=z;function $(n){return O(n)&&y(n)}function C(n){return function(){return n}}function K(n){return function(r){var t=n(r);return"number"==typeof t&&t>=0&&t<=m}}function J(n){return function(r){return null==r?void 0:r[n]}}var G=J("byteLength"),H=K(G),Q=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var X=c?function(n){return h?h(n)&&!q(n):H(n)&&Q.test(a.call(n))}:C(!1),Y=J("length");function Z(n,r){r=function(n){for(var r={},t=n.length,e=0;e<t;++e)r[n[e]]=!0;return{contains:function(n){return r[n]},push:function(t){return r[t]=!0,n.push(t)}}}(r);var t=b.length,u=n.constructor,o=D(u)&&u.prototype||e,i="constructor";for(W(n,i)&&!r.contains(i)&&r.push(i);t--;)(i=b[t])in n&&n[i]!==o[i]&&!r.contains(i)&&r.push(i)}function nn(n){if(!_(n))return[];if(p)return p(n);var r=[];for(var t in n)W(n,t)&&r.push(t);return g&&Z(n,r),r}function rn(n,r){var t=nn(r),e=t.length;if(null==n)return!e;for(var u=Object(n),o=0;o<e;o++){var i=t[o];if(r[i]!==u[i]||!(i in u))return!1}return!0}function tn(n){return n instanceof tn?n:this instanceof tn?void(this._wrapped=n):new tn(n)}function en(n){return new Uint8Array(n.buffer||n,n.byteOffset||0,G(n))}tn.VERSION=n,tn.prototype.value=function(){return this._wrapped},tn.prototype.valueOf=tn.prototype.toJSON=tn.prototype.value,tn.prototype.toString=function(){return String(this._wrapped)};var un="[object DataView]";function on(n,r,t,e){if(n===r)return 0!==n||1/n==1/r;if(null==n||null==r)return!1;if(n!=n)return r!=r;var o=typeof n;return("function"===o||"object"===o||"object"==typeof r)&&function n(r,t,e,o){r instanceof tn&&(r=r._wrapped);t instanceof tn&&(t=t._wrapped);var i=a.call(r);if(i!==a.call(t))return!1;if(F&&"[object Object]"==i&&q(r)){if(!q(t))return!1;i=un}switch(i){case"[object RegExp]":case"[object String]":return""+r==""+t;case"[object Number]":return+r!=+r?+t!=+t:0==+r?1/+r==1/t:+r==+t;case"[object Date]":case"[object Boolean]":return+r==+t;case"[object Symbol]":return u.valueOf.call(r)===u.valueOf.call(t);case"[object ArrayBuffer]":case un:return n(en(r),en(t),e,o)}var f="[object Array]"===i;if(!f&&X(r)){if(G(r)!==G(t))return!1;if(r.buffer===t.buffer&&r.byteOffset===t.byteOffset)return!0;f=!0}if(!f){if("object"!=typeof r||"object"!=typeof t)return!1;var c=r.constructor,l=t.constructor;if(c!==l&&!(D(c)&&c instanceof c&&D(l)&&l instanceof l)&&"constructor"in r&&"constructor"in t)return!1}o=o||[];var s=(e=e||[]).length;for(;s--;)if(e[s]===r)return o[s]===t;if(e.push(r),o.push(t),f){if((s=r.length)!==t.length)return!1;for(;s--;)if(!on(r[s],t[s],e,o))return!1}else{var p,v=nn(r);if(s=v.length,nn(t).length!==s)return!1;for(;s--;)if(p=v[s],!W(t,p)||!on(r[p],t[p],e,o))return!1}return e.pop(),o.pop(),!0}(n,r,t,e)}function an(n){if(!_(n))return[];var r=[];for(var t in n)r.push(t);return g&&Z(n,r),r}function fn(n){var r=Y(n);return function(t){if(null==t)return!1;var e=an(t);if(Y(e))return!1;for(var u=0;u<r;u++)if(!D(t[n[u]]))return!1;return n!==hn||!D(t[cn])}}var cn="forEach",ln="has",sn=["clear","delete"],pn=["get",ln,"set"],vn=sn.concat(cn,pn),hn=sn.concat(pn),yn=["add"].concat(sn,cn,ln),dn=V?fn(vn):x("Map"),gn=V?fn(hn):x("WeakMap"),bn=V?fn(yn):x("Set"),mn=x("WeakSet");function jn(n){for(var r=nn(n),t=r.length,e=Array(t),u=0;u<t;u++)e[u]=n[r[u]];return e}function _n(n){for(var r={},t=nn(n),e=0,u=t.length;e<u;e++)r[n[t[e]]]=t[e];return r}function wn(n){var r=[];for(var t in n)D(n[t])&&r.push(t);return r.sort()}function An(n,r){return function(t){var e=arguments.length;if(r&&(t=Object(t)),e<2||null==t)return t;for(var u=1;u<e;u++)for(var o=arguments[u],i=n(o),a=i.length,f=0;f<a;f++){var c=i[f];r&&void 0!==t[c]||(t[c]=o[c])}return t}}var xn=An(an),Sn=An(nn),On=An(an,!0);function Mn(n){if(!_(n))return{};if(v)return v(n);var r=function(){};r.prototype=n;var t=new r;return r.prototype=null,t}function En(n){return _(n)?U(n)?n.slice():xn({},n):n}function Bn(n){return U(n)?n:[n]}function Nn(n){return tn.toPath(n)}function In(n,r){for(var t=r.length,e=0;e<t;e++){if(null==n)return;n=n[r[e]]}return t?n:void 0}function Tn(n,r,t){var e=In(n,Nn(r));return w(e)?t:e}function kn(n){return n}function Dn(n){return n=Sn({},n),function(r){return rn(r,n)}}function Rn(n){return n=Nn(n),function(r){return In(r,n)}}function Fn(n,r,t){if(void 0===r)return n;switch(null==t?3:t){case 1:return function(t){return n.call(r,t)};case 3:return function(t,e,u){return n.call(r,t,e,u)};case 4:return function(t,e,u,o){return n.call(r,t,e,u,o)}}return function(){return n.apply(r,arguments)}}function Vn(n,r,t){return null==n?kn:D(n)?Fn(n,r,t):_(n)&&!U(n)?Dn(n):Rn(n)}function Pn(n,r){return Vn(n,r,1/0)}function qn(n,r,t){return tn.iteratee!==Pn?tn.iteratee(n,r):Vn(n,r,t)}function Un(){}function Wn(n,r){return null==r&&(r=n,n=0),n+Math.floor(Math.random()*(r-n+1))}tn.toPath=Bn,tn.iteratee=Pn;var zn=Date.now||function(){return(new Date).getTime()};function Ln(n){var r=function(r){return n[r]},t="(?:"+nn(n).join("|")+")",e=RegExp(t),u=RegExp(t,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,r):n}}var $n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},Cn=Ln($n),Kn=Ln(_n($n)),Jn=tn.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},Gn=/(.)^/,Hn={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},Qn=/\\|'|\r|\n|\u2028|\u2029/g;function Xn(n){return"\\"+Hn[n]}var Yn=/^\s*(\w|\$)+\s*$/;var Zn=0;function nr(n,r,t,e,u){if(!(e instanceof r))return n.apply(t,u);var o=Mn(n.prototype),i=n.apply(o,u);return _(i)?i:o}var rr=j((function(n,r){var t=rr.placeholder,e=function(){for(var u=0,o=r.length,i=Array(o),a=0;a<o;a++)i[a]=r[a]===t?arguments[u++]:r[a];for(;u<arguments.length;)i.push(arguments[u++]);return nr(n,e,this,this,i)};return e}));rr.placeholder=tn;var tr=j((function(n,r,t){if(!D(n))throw new TypeError("Bind must be called on a function");var e=j((function(u){return nr(n,e,r,this,t.concat(u))}));return e})),er=K(Y);function ur(n,r,t,e){if(e=e||[],r||0===r){if(r<=0)return e.concat(n)}else r=1/0;for(var u=e.length,o=0,i=Y(n);o<i;o++){var a=n[o];if(er(a)&&(U(a)||L(a)))if(r>1)ur(a,r-1,t,e),u=e.length;else for(var f=0,c=a.length;f<c;)e[u++]=a[f++];else t||(e[u++]=a)}return e}var or=j((function(n,r){var t=(r=ur(r,!1,!1)).length;if(t<1)throw new Error("bindAll must be passed function names");for(;t--;){var e=r[t];n[e]=tr(n[e],n)}return n}));var ir=j((function(n,r,t){return setTimeout((function(){return n.apply(null,t)}),r)})),ar=rr(ir,tn,1);function fr(n){return function(){return!n.apply(this,arguments)}}function cr(n,r){var t;return function(){return--n>0&&(t=r.apply(this,arguments)),n<=1&&(r=null),t}}var lr=rr(cr,2);function sr(n,r,t){r=qn(r,t);for(var e,u=nn(n),o=0,i=u.length;o<i;o++)if(r(n[e=u[o]],e,n))return e}function pr(n){return function(r,t,e){t=qn(t,e);for(var u=Y(r),o=n>0?0:u-1;o>=0&&o<u;o+=n)if(t(r[o],o,r))return o;return-1}}var vr=pr(1),hr=pr(-1);function yr(n,r,t,e){for(var u=(t=qn(t,e,1))(r),o=0,i=Y(n);o<i;){var a=Math.floor((o+i)/2);t(n[a])<u?o=a+1:i=a}return o}function dr(n,r,t){return function(e,u,o){var a=0,f=Y(e);if("number"==typeof o)n>0?a=o>=0?o:Math.max(o+f,a):f=o>=0?Math.min(o+1,f):o+f+1;else if(t&&o&&f)return e[o=t(e,u)]===u?o:-1;if(u!=u)return(o=r(i.call(e,a,f),$))>=0?o+a:-1;for(o=n>0?a:f-1;o>=0&&o<f;o+=n)if(e[o]===u)return o;return-1}}var gr=dr(1,vr,yr),br=dr(-1,hr);function mr(n,r,t){var e=(er(n)?vr:sr)(n,r,t);if(void 0!==e&&-1!==e)return n[e]}function jr(n,r,t){var e,u;if(r=Fn(r,t),er(n))for(e=0,u=n.length;e<u;e++)r(n[e],e,n);else{var o=nn(n);for(e=0,u=o.length;e<u;e++)r(n[o[e]],o[e],n)}return n}function _r(n,r,t){r=qn(r,t);for(var e=!er(n)&&nn(n),u=(e||n).length,o=Array(u),i=0;i<u;i++){var a=e?e[i]:i;o[i]=r(n[a],a,n)}return o}function wr(n){var r=function(r,t,e,u){var o=!er(r)&&nn(r),i=(o||r).length,a=n>0?0:i-1;for(u||(e=r[o?o[a]:a],a+=n);a>=0&&a<i;a+=n){var f=o?o[a]:a;e=t(e,r[f],f,r)}return e};return function(n,t,e,u){var o=arguments.length>=3;return r(n,Fn(t,u,4),e,o)}}var Ar=wr(1),xr=wr(-1);function Sr(n,r,t){var e=[];return r=qn(r,t),jr(n,(function(n,t,u){r(n,t,u)&&e.push(n)})),e}function Or(n,r,t){r=qn(r,t);for(var e=!er(n)&&nn(n),u=(e||n).length,o=0;o<u;o++){var i=e?e[o]:o;if(!r(n[i],i,n))return!1}return!0}function Mr(n,r,t){r=qn(r,t);for(var e=!er(n)&&nn(n),u=(e||n).length,o=0;o<u;o++){var i=e?e[o]:o;if(r(n[i],i,n))return!0}return!1}function Er(n,r,t,e){return er(n)||(n=jn(n)),("number"!=typeof t||e)&&(t=0),gr(n,r,t)>=0}var Br=j((function(n,r,t){var e,u;return D(r)?u=r:(r=Nn(r),e=r.slice(0,-1),r=r[r.length-1]),_r(n,(function(n){var o=u;if(!o){if(e&&e.length&&(n=In(n,e)),null==n)return;o=n[r]}return null==o?o:o.apply(n,t)}))}));function Nr(n,r){return _r(n,Rn(r))}function Ir(n,r,t){var e,u,o=-1/0,i=-1/0;if(null==r||"number"==typeof r&&"object"!=typeof n[0]&&null!=n)for(var a=0,f=(n=er(n)?n:jn(n)).length;a<f;a++)null!=(e=n[a])&&e>o&&(o=e);else r=qn(r,t),jr(n,(function(n,t,e){((u=r(n,t,e))>i||u===-1/0&&o===-1/0)&&(o=n,i=u)}));return o}function Tr(n,r,t){if(null==r||t)return er(n)||(n=jn(n)),n[Wn(n.length-1)];var e=er(n)?En(n):jn(n),u=Y(e);r=Math.max(Math.min(r,u),0);for(var o=u-1,i=0;i<r;i++){var a=Wn(i,o),f=e[i];e[i]=e[a],e[a]=f}return e.slice(0,r)}function kr(n,r){return function(t,e,u){var o=r?[[],[]]:{};return e=qn(e,u),jr(t,(function(r,u){var i=e(r,u,t);n(o,r,i)})),o}}var Dr=kr((function(n,r,t){W(n,t)?n[t].push(r):n[t]=[r]})),Rr=kr((function(n,r,t){n[t]=r})),Fr=kr((function(n,r,t){W(n,t)?n[t]++:n[t]=1})),Vr=kr((function(n,r,t){n[t?0:1].push(r)}),!0),Pr=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function qr(n,r,t){return r in t}var Ur=j((function(n,r){var t={},e=r[0];if(null==n)return t;D(e)?(r.length>1&&(e=Fn(e,r[1])),r=an(n)):(e=qr,r=ur(r,!1,!1),n=Object(n));for(var u=0,o=r.length;u<o;u++){var i=r[u],a=n[i];e(a,i,n)&&(t[i]=a)}return t})),Wr=j((function(n,r){var t,e=r[0];return D(e)?(e=fr(e),r.length>1&&(t=r[1])):(r=_r(ur(r,!1,!1),String),e=function(n,t){return!Er(r,t)}),Ur(n,e,t)}));function zr(n,r,t){return i.call(n,0,Math.max(0,n.length-(null==r||t?1:r)))}function Lr(n,r,t){return null==n||n.length<1?null==r||t?void 0:[]:null==r||t?n[0]:zr(n,n.length-r)}function $r(n,r,t){return i.call(n,null==r||t?1:r)}var Cr=j((function(n,r){return r=ur(r,!0,!0),Sr(n,(function(n){return!Er(r,n)}))})),Kr=j((function(n,r){return Cr(n,r)}));function Jr(n,r,t,e){A(r)||(e=t,t=r,r=!1),null!=t&&(t=qn(t,e));for(var u=[],o=[],i=0,a=Y(n);i<a;i++){var f=n[i],c=t?t(f,i,n):f;r&&!t?(i&&o===c||u.push(f),o=c):t?Er(o,c)||(o.push(c),u.push(f)):Er(u,f)||u.push(f)}return u}var Gr=j((function(n){return Jr(ur(n,!0,!0))}));function Hr(n){for(var r=n&&Ir(n,Y).length||0,t=Array(r),e=0;e<r;e++)t[e]=Nr(n,e);return t}var Qr=j(Hr);function Xr(n,r){return n._chain?tn(r).chain():r}function Yr(n){return jr(wn(n),(function(r){var t=tn[r]=n[r];tn.prototype[r]=function(){var n=[this._wrapped];return o.apply(n,arguments),Xr(this,t.apply(tn,n))}})),tn}jr(["pop","push","reverse","shift","sort","splice","unshift"],(function(n){var r=t[n];tn.prototype[n]=function(){var t=this._wrapped;return null!=t&&(r.apply(t,arguments),"shift"!==n&&"splice"!==n||0!==t.length||delete t[0]),Xr(this,t)}})),jr(["concat","join","slice"],(function(n){var r=t[n];tn.prototype[n]=function(){var n=this._wrapped;return null!=n&&(n=r.apply(n,arguments)),Xr(this,n)}}));var Zr=Yr({__proto__:null,VERSION:n,restArguments:j,isObject:_,isNull:function(n){return null===n},isUndefined:w,isBoolean:A,isElement:function(n){return!(!n||1!==n.nodeType)},isString:S,isNumber:O,isDate:M,isRegExp:E,isError:B,isSymbol:N,isArrayBuffer:I,isDataView:q,isArray:U,isFunction:D,isArguments:L,isFinite:function(n){return!N(n)&&d(n)&&!isNaN(parseFloat(n))},isNaN:$,isTypedArray:X,isEmpty:function(n){if(null==n)return!0;var r=Y(n);return"number"==typeof r&&(U(n)||S(n)||L(n))?0===r:0===Y(nn(n))},isMatch:rn,isEqual:function(n,r){return on(n,r)},isMap:dn,isWeakMap:gn,isSet:bn,isWeakSet:mn,keys:nn,allKeys:an,values:jn,pairs:function(n){for(var r=nn(n),t=r.length,e=Array(t),u=0;u<t;u++)e[u]=[r[u],n[r[u]]];return e},invert:_n,functions:wn,methods:wn,extend:xn,extendOwn:Sn,assign:Sn,defaults:On,create:function(n,r){var t=Mn(n);return r&&Sn(t,r),t},clone:En,tap:function(n,r){return r(n),n},get:Tn,has:function(n,r){for(var t=(r=Nn(r)).length,e=0;e<t;e++){var u=r[e];if(!W(n,u))return!1;n=n[u]}return!!t},mapObject:function(n,r,t){r=qn(r,t);for(var e=nn(n),u=e.length,o={},i=0;i<u;i++){var a=e[i];o[a]=r(n[a],a,n)}return o},identity:kn,constant:C,noop:Un,toPath:Bn,property:Rn,propertyOf:function(n){return null==n?Un:function(r){return Tn(n,r)}},matcher:Dn,matches:Dn,times:function(n,r,t){var e=Array(Math.max(0,n));r=Fn(r,t,1);for(var u=0;u<n;u++)e[u]=r(u);return e},random:Wn,now:zn,escape:Cn,unescape:Kn,templateSettings:Jn,template:function(n,r,t){!r&&t&&(r=t),r=On({},r,tn.templateSettings);var e=RegExp([(r.escape||Gn).source,(r.interpolate||Gn).source,(r.evaluate||Gn).source].join("|")+"|$","g"),u=0,o="__p+='";n.replace(e,(function(r,t,e,i,a){return o+=n.slice(u,a).replace(Qn,Xn),u=a+r.length,t?o+="'+\n((__t=("+t+"))==null?'':_.escape(__t))+\n'":e?o+="'+\n((__t=("+e+"))==null?'':__t)+\n'":i&&(o+="';\n"+i+"\n__p+='"),r})),o+="';\n";var i,a=r.variable;if(a){if(!Yn.test(a))throw new Error("variable is not a bare identifier: "+a)}else o="with(obj||{}){\n"+o+"}\n",a="obj";o="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{i=new Function(a,"_",o)}catch(n){throw n.source=o,n}var f=function(n){return i.call(this,n,tn)};return f.source="function("+a+"){\n"+o+"}",f},result:function(n,r,t){var e=(r=Nn(r)).length;if(!e)return D(t)?t.call(n):t;for(var u=0;u<e;u++){var o=null==n?void 0:n[r[u]];void 0===o&&(o=t,u=e),n=D(o)?o.call(n):o}return n},uniqueId:function(n){var r=++Zn+"";return n?n+r:r},chain:function(n){var r=tn(n);return r._chain=!0,r},iteratee:Pn,partial:rr,bind:tr,bindAll:or,memoize:function(n,r){var t=function(e){var u=t.cache,o=""+(r?r.apply(this,arguments):e);return W(u,o)||(u[o]=n.apply(this,arguments)),u[o]};return t.cache={},t},delay:ir,defer:ar,throttle:function(n,r,t){var e,u,o,i,a=0;t||(t={});var f=function(){a=!1===t.leading?0:zn(),e=null,i=n.apply(u,o),e||(u=o=null)},c=function(){var c=zn();a||!1!==t.leading||(a=c);var l=r-(c-a);return u=this,o=arguments,l<=0||l>r?(e&&(clearTimeout(e),e=null),a=c,i=n.apply(u,o),e||(u=o=null)):e||!1===t.trailing||(e=setTimeout(f,l)),i};return c.cancel=function(){clearTimeout(e),a=0,e=u=o=null},c},debounce:function(n,r,t){var e,u,o,i,a,f=function(){var c=zn()-u;r>c?e=setTimeout(f,r-c):(e=null,t||(i=n.apply(a,o)),e||(o=a=null))},c=j((function(c){return a=this,o=c,u=zn(),e||(e=setTimeout(f,r),t&&(i=n.apply(a,o))),i}));return c.cancel=function(){clearTimeout(e),e=o=a=null},c},wrap:function(n,r){return rr(r,n)},negate:fr,compose:function(){var n=arguments,r=n.length-1;return function(){for(var t=r,e=n[r].apply(this,arguments);t--;)e=n[t].call(this,e);return e}},after:function(n,r){return function(){if(--n<1)return r.apply(this,arguments)}},before:cr,once:lr,findKey:sr,findIndex:vr,findLastIndex:hr,sortedIndex:yr,indexOf:gr,lastIndexOf:br,find:mr,detect:mr,findWhere:function(n,r){return mr(n,Dn(r))},each:jr,forEach:jr,map:_r,collect:_r,reduce:Ar,foldl:Ar,inject:Ar,reduceRight:xr,foldr:xr,filter:Sr,select:Sr,reject:function(n,r,t){return Sr(n,fr(qn(r)),t)},every:Or,all:Or,some:Mr,any:Mr,contains:Er,includes:Er,include:Er,invoke:Br,pluck:Nr,where:function(n,r){return Sr(n,Dn(r))},max:Ir,min:function(n,r,t){var e,u,o=1/0,i=1/0;if(null==r||"number"==typeof r&&"object"!=typeof n[0]&&null!=n)for(var a=0,f=(n=er(n)?n:jn(n)).length;a<f;a++)null!=(e=n[a])&&e<o&&(o=e);else r=qn(r,t),jr(n,(function(n,t,e){((u=r(n,t,e))<i||u===1/0&&o===1/0)&&(o=n,i=u)}));return o},shuffle:function(n){return Tr(n,1/0)},sample:Tr,sortBy:function(n,r,t){var e=0;return r=qn(r,t),Nr(_r(n,(function(n,t,u){return{value:n,index:e++,criteria:r(n,t,u)}})).sort((function(n,r){var t=n.criteria,e=r.criteria;if(t!==e){if(t>e||void 0===t)return 1;if(t<e||void 0===e)return-1}return n.index-r.index})),"value")},groupBy:Dr,indexBy:Rr,countBy:Fr,partition:Vr,toArray:function(n){return n?U(n)?i.call(n):S(n)?n.match(Pr):er(n)?_r(n,kn):jn(n):[]},size:function(n){return null==n?0:er(n)?n.length:nn(n).length},pick:Ur,omit:Wr,first:Lr,head:Lr,take:Lr,initial:zr,last:function(n,r,t){return null==n||n.length<1?null==r||t?void 0:[]:null==r||t?n[n.length-1]:$r(n,Math.max(0,n.length-r))},rest:$r,tail:$r,drop:$r,compact:function(n){return Sr(n,Boolean)},flatten:function(n,r){return ur(n,r,!1)},without:Kr,uniq:Jr,unique:Jr,union:Gr,intersection:function(n){for(var r=[],t=arguments.length,e=0,u=Y(n);e<u;e++){var o=n[e];if(!Er(r,o)){var i;for(i=1;i<t&&Er(arguments[i],o);i++);i===t&&r.push(o)}}return r},difference:Cr,unzip:Hr,transpose:Hr,zip:Qr,object:function(n,r){for(var t={},e=0,u=Y(n);e<u;e++)r?t[n[e]]=r[e]:t[n[e][0]]=n[e][1];return t},range:function(n,r,t){null==r&&(r=n||0,n=0),t||(t=r<n?-1:1);for(var e=Math.max(Math.ceil((r-n)/t),0),u=Array(e),o=0;o<e;o++,n+=t)u[o]=n;return u},chunk:function(n,r){if(null==r||r<1)return[];for(var t=[],e=0,u=n.length;e<u;)t.push(i.call(n,e,e+=r));return t},mixin:Yr,default:tn});return Zr._=Zr,Zr}));
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/_build/html/_static/underscore.js
underscore.js
if (!Scorer) { /** * Simple result scoring code. */ var Scorer = { // Implement the following function to further tweak the score for each result // The function takes a result array [filename, title, anchor, descr, score] // and returns the new score. /* score: function(result) { return result[4]; }, */ // query matches the full name of an object objNameMatch: 11, // or matches in the last dotted part of the object name objPartialMatch: 6, // Additive scores depending on the priority of the object objPrio: {0: 15, // used to be importantResults 1: 5, // used to be objectResults 2: -5}, // used to be unimportantResults // Used when the priority is not in the mapping. objPrioDefault: 0, // query found in title title: 15, partialTitle: 7, // query found in terms term: 5, partialTerm: 2 }; } if (!splitQuery) { function splitQuery(query) { return query.split(/\s+/); } } /** * Search Module */ var Search = { _index : null, _queued_query : null, _pulse_status : -1, htmlToText : function(htmlString) { var virtualDocument = document.implementation.createHTMLDocument('virtual'); var htmlElement = $(htmlString, virtualDocument); htmlElement.find('.headerlink').remove(); docContent = htmlElement.find('[role=main]')[0]; if(docContent === undefined) { console.warn("Content block not found. Sphinx search tries to obtain it " + "via '[role=main]'. Could you check your theme or template."); return ""; } return docContent.textContent || docContent.innerText; }, init : function() { var params = $.getQueryParameters(); if (params.q) { var query = params.q[0]; $('input[name="q"]')[0].value = query; this.performSearch(query); } }, loadIndex : function(url) { $.ajax({type: "GET", url: url, data: null, dataType: "script", cache: true, complete: function(jqxhr, textstatus) { if (textstatus != "success") { document.getElementById("searchindexloader").src = url; } }}); }, setIndex : function(index) { var q; this._index = index; if ((q = this._queued_query) !== null) { this._queued_query = null; Search.query(q); } }, hasIndex : function() { return this._index !== null; }, deferQuery : function(query) { this._queued_query = query; }, stopPulse : function() { this._pulse_status = 0; }, startPulse : function() { if (this._pulse_status >= 0) return; function pulse() { var i; Search._pulse_status = (Search._pulse_status + 1) % 4; var dotString = ''; for (i = 0; i < Search._pulse_status; i++) dotString += '.'; Search.dots.text(dotString); if (Search._pulse_status > -1) window.setTimeout(pulse, 500); } pulse(); }, /** * perform a search for something (or wait until index is loaded) */ performSearch : function(query) { // create the required interface elements this.out = $('#search-results'); this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out); this.dots = $('<span></span>').appendTo(this.title); this.status = $('<p class="search-summary">&nbsp;</p>').appendTo(this.out); this.output = $('<ul class="search"/>').appendTo(this.out); $('#search-progress').text(_('Preparing search...')); this.startPulse(); // index already loaded, the browser was quick! if (this.hasIndex()) this.query(query); else this.deferQuery(query); }, /** * execute search (requires search index to be loaded) */ query : function(query) { var i; // stem the searchterms and add them to the correct list var stemmer = new Stemmer(); var searchterms = []; var excluded = []; var hlterms = []; var tmp = splitQuery(query); var objectterms = []; for (i = 0; i < tmp.length; i++) { if (tmp[i] !== "") { objectterms.push(tmp[i].toLowerCase()); } if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i] === "") { // skip this "word" continue; } // stem the word var word = stemmer.stemWord(tmp[i].toLowerCase()); // prevent stemmer from cutting word smaller than two chars if(word.length < 3 && tmp[i].length >= 3) { word = tmp[i]; } var toAppend; // select the correct list if (word[0] == '-') { toAppend = excluded; word = word.substr(1); } else { toAppend = searchterms; hlterms.push(tmp[i].toLowerCase()); } // only add if not already in the list if (!$u.contains(toAppend, word)) toAppend.push(word); } var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" ")); // console.debug('SEARCH: searching for:'); // console.info('required: ', searchterms); // console.info('excluded: ', excluded); // prepare search var terms = this._index.terms; var titleterms = this._index.titleterms; // array of [filename, title, anchor, descr, score] var results = []; $('#search-progress').empty(); // lookup as object for (i = 0; i < objectterms.length; i++) { var others = [].concat(objectterms.slice(0, i), objectterms.slice(i+1, objectterms.length)); results = results.concat(this.performObjectSearch(objectterms[i], others)); } // lookup as search terms in fulltext results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms)); // let the scorer override scores with a custom scoring function if (Scorer.score) { for (i = 0; i < results.length; i++) results[i][4] = Scorer.score(results[i]); } // now sort the results by score (in opposite order of appearance, since the // display function below uses pop() to retrieve items) and then // alphabetically results.sort(function(a, b) { var left = a[4]; var right = b[4]; if (left > right) { return 1; } else if (left < right) { return -1; } else { // same score: sort alphabetically left = a[1].toLowerCase(); right = b[1].toLowerCase(); return (left > right) ? -1 : ((left < right) ? 1 : 0); } }); // for debugging //Search.lastresults = results.slice(); // a copy //console.info('search results:', Search.lastresults); // print the results var resultCount = results.length; function displayNextItem() { // results left, load the summary and display it if (results.length) { var item = results.pop(); var listItem = $('<li></li>'); var requestUrl = ""; var linkUrl = ""; if (DOCUMENTATION_OPTIONS.BUILDER === 'dirhtml') { // dirhtml builder var dirname = item[0] + '/'; if (dirname.match(/\/index\/$/)) { dirname = dirname.substring(0, dirname.length-6); } else if (dirname == 'index/') { dirname = ''; } requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + dirname; linkUrl = requestUrl; } else { // normal html builders requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX; linkUrl = item[0] + DOCUMENTATION_OPTIONS.LINK_SUFFIX; } listItem.append($('<a/>').attr('href', linkUrl + highlightstring + item[2]).html(item[1])); if (item[3]) { listItem.append($('<span> (' + item[3] + ')</span>')); Search.output.append(listItem); setTimeout(function() { displayNextItem(); }, 5); } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) { $.ajax({url: requestUrl, dataType: "text", complete: function(jqxhr, textstatus) { var data = jqxhr.responseText; if (data !== '' && data !== undefined) { var summary = Search.makeSearchSummary(data, searchterms, hlterms); if (summary) { listItem.append(summary); } } Search.output.append(listItem); setTimeout(function() { displayNextItem(); }, 5); }}); } else { // no source available, just display title Search.output.append(listItem); setTimeout(function() { displayNextItem(); }, 5); } } // search finished, update title and status message else { Search.stopPulse(); Search.title.text(_('Search Results')); if (!resultCount) Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.')); else Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount)); Search.status.fadeIn(500); } } displayNextItem(); }, /** * search for object names */ performObjectSearch : function(object, otherterms) { var filenames = this._index.filenames; var docnames = this._index.docnames; var objects = this._index.objects; var objnames = this._index.objnames; var titles = this._index.titles; var i; var results = []; for (var prefix in objects) { for (var iMatch = 0; iMatch != objects[prefix].length; ++iMatch) { var match = objects[prefix][iMatch]; var name = match[4]; var fullname = (prefix ? prefix + '.' : '') + name; var fullnameLower = fullname.toLowerCase() if (fullnameLower.indexOf(object) > -1) { var score = 0; var parts = fullnameLower.split('.'); // check for different match types: exact matches of full name or // "last name" (i.e. last dotted part) if (fullnameLower == object || parts[parts.length - 1] == object) { score += Scorer.objNameMatch; // matches in last name } else if (parts[parts.length - 1].indexOf(object) > -1) { score += Scorer.objPartialMatch; } var objname = objnames[match[1]][2]; var title = titles[match[0]]; // If more than one term searched for, we require other words to be // found in the name/title/description if (otherterms.length > 0) { var haystack = (prefix + ' ' + name + ' ' + objname + ' ' + title).toLowerCase(); var allfound = true; for (i = 0; i < otherterms.length; i++) { if (haystack.indexOf(otherterms[i]) == -1) { allfound = false; break; } } if (!allfound) { continue; } } var descr = objname + _(', in ') + title; var anchor = match[3]; if (anchor === '') anchor = fullname; else if (anchor == '-') anchor = objnames[match[1]][1] + '-' + fullname; // add custom score for some objects according to scorer if (Scorer.objPrio.hasOwnProperty(match[2])) { score += Scorer.objPrio[match[2]]; } else { score += Scorer.objPrioDefault; } results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]); } } } return results; }, /** * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */ escapeRegExp : function(string) { return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string }, /** * search for full-text terms in the index */ performTermsSearch : function(searchterms, excluded, terms, titleterms) { var docnames = this._index.docnames; var filenames = this._index.filenames; var titles = this._index.titles; var i, j, file; var fileMap = {}; var scoreMap = {}; var results = []; // perform the search on the required terms for (i = 0; i < searchterms.length; i++) { var word = searchterms[i]; var files = []; var _o = [ {files: terms[word], score: Scorer.term}, {files: titleterms[word], score: Scorer.title} ]; // add support for partial matches if (word.length > 2) { var word_regex = this.escapeRegExp(word); for (var w in terms) { if (w.match(word_regex) && !terms[word]) { _o.push({files: terms[w], score: Scorer.partialTerm}) } } for (var w in titleterms) { if (w.match(word_regex) && !titleterms[word]) { _o.push({files: titleterms[w], score: Scorer.partialTitle}) } } } // no match but word was a required one if ($u.every(_o, function(o){return o.files === undefined;})) { break; } // found search word in contents $u.each(_o, function(o) { var _files = o.files; if (_files === undefined) return if (_files.length === undefined) _files = [_files]; files = files.concat(_files); // set score for the word in each file to Scorer.term for (j = 0; j < _files.length; j++) { file = _files[j]; if (!(file in scoreMap)) scoreMap[file] = {}; scoreMap[file][word] = o.score; } }); // create the mapping for (j = 0; j < files.length; j++) { file = files[j]; if (file in fileMap && fileMap[file].indexOf(word) === -1) fileMap[file].push(word); else fileMap[file] = [word]; } } // now check if the files don't contain excluded terms for (file in fileMap) { var valid = true; // check if all requirements are matched var filteredTermCount = // as search terms with length < 3 are discarded: ignore searchterms.filter(function(term){return term.length > 2}).length if ( fileMap[file].length != searchterms.length && fileMap[file].length != filteredTermCount ) continue; // ensure that none of the excluded terms is in the search result for (i = 0; i < excluded.length; i++) { if (terms[excluded[i]] == file || titleterms[excluded[i]] == file || $u.contains(terms[excluded[i]] || [], file) || $u.contains(titleterms[excluded[i]] || [], file)) { valid = false; break; } } // if we have still a valid result we can add it to the result list if (valid) { // select one (max) score for the file. // for better ranking, we should calculate ranking by using words statistics like basic tf-idf... var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]})); results.push([docnames[file], titles[file], '', null, score, filenames[file]]); } } return results; }, /** * helper function to return a node containing the * search summary for a given text. keywords is a list * of stemmed words, hlwords is the list of normal, unstemmed * words. the first one is used to find the occurrence, the * latter for highlighting it. */ makeSearchSummary : function(htmlText, keywords, hlwords) { var text = Search.htmlToText(htmlText); if (text == "") { return null; } var textLower = text.toLowerCase(); var start = 0; $.each(keywords, function() { var i = textLower.indexOf(this.toLowerCase()); if (i > -1) start = i; }); start = Math.max(start - 120, 0); var excerpt = ((start > 0) ? '...' : '') + $.trim(text.substr(start, 240)) + ((start + 240 - text.length) ? '...' : ''); var rv = $('<p class="context"></p>').text(excerpt); $.each(hlwords, function() { rv = rv.highlightText(this, 'highlighted'); }); return rv; } }; $(document).ready(function() { Search.init(); });
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/_build/html/_static/searchtools.js
searchtools.js
!function(n){var e={};function t(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return n[i].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=n,t.c=e,t.d=function(n,e,i){t.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:i})},t.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,e){if(1&e&&(n=t(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var i=Object.create(null);if(t.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)t.d(i,o,function(e){return n[e]}.bind(null,o));return i},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},t.p="",t(t.s=0)}([function(n,e,t){t(1),n.exports=t(3)},function(n,e,t){(function(){var e="undefined"!=typeof window?window.jQuery:t(2);n.exports.ThemeNav={navBar:null,win:null,winScroll:!1,winResize:!1,linkScroll:!1,winPosition:0,winHeight:null,docHeight:null,isRunning:!1,enable:function(n){var t=this;void 0===n&&(n=!0),t.isRunning||(t.isRunning=!0,e((function(e){t.init(e),t.reset(),t.win.on("hashchange",t.reset),n&&t.win.on("scroll",(function(){t.linkScroll||t.winScroll||(t.winScroll=!0,requestAnimationFrame((function(){t.onScroll()})))})),t.win.on("resize",(function(){t.winResize||(t.winResize=!0,requestAnimationFrame((function(){t.onResize()})))})),t.onResize()})))},enableSticky:function(){this.enable(!0)},init:function(n){n(document);var e=this;this.navBar=n("div.wy-side-scroll:first"),this.win=n(window),n(document).on("click","[data-toggle='wy-nav-top']",(function(){n("[data-toggle='wy-nav-shift']").toggleClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift")})).on("click",".wy-menu-vertical .current ul li a",(function(){var t=n(this);n("[data-toggle='wy-nav-shift']").removeClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift"),e.toggleCurrent(t),e.hashChange()})).on("click","[data-toggle='rst-current-version']",(function(){n("[data-toggle='rst-versions']").toggleClass("shift-up")})),n("table.docutils:not(.field-list,.footnote,.citation)").wrap("<div class='wy-table-responsive'></div>"),n("table.docutils.footnote").wrap("<div class='wy-table-responsive footnote'></div>"),n("table.docutils.citation").wrap("<div class='wy-table-responsive citation'></div>"),n(".wy-menu-vertical ul").not(".simple").siblings("a").each((function(){var t=n(this);expand=n('<button class="toctree-expand" title="Open/close menu"></button>'),expand.on("click",(function(n){return e.toggleCurrent(t),n.stopPropagation(),!1})),t.prepend(expand)}))},reset:function(){var n=encodeURI(window.location.hash)||"#";try{var e=$(".wy-menu-vertical"),t=e.find('[href="'+n+'"]');if(0===t.length){var i=$('.document [id="'+n.substring(1)+'"]').closest("div.section");0===(t=e.find('[href="#'+i.attr("id")+'"]')).length&&(t=e.find('[href="#"]'))}if(t.length>0){$(".wy-menu-vertical .current").removeClass("current").attr("aria-expanded","false"),t.addClass("current").attr("aria-expanded","true"),t.closest("li.toctree-l1").parent().addClass("current").attr("aria-expanded","true");for(let n=1;n<=10;n++)t.closest("li.toctree-l"+n).addClass("current").attr("aria-expanded","true");t[0].scrollIntoView()}}catch(n){console.log("Error expanding nav for anchor",n)}},onScroll:function(){this.winScroll=!1;var n=this.win.scrollTop(),e=n+this.winHeight,t=this.navBar.scrollTop()+(n-this.winPosition);n<0||e>this.docHeight||(this.navBar.scrollTop(t),this.winPosition=n)},onResize:function(){this.winResize=!1,this.winHeight=this.win.height(),this.docHeight=$(document).height()},hashChange:function(){this.linkScroll=!0,this.win.one("hashchange",(function(){this.linkScroll=!1}))},toggleCurrent:function(n){var e=n.closest("li");e.siblings("li.current").removeClass("current").attr("aria-expanded","false"),e.siblings().find("li.current").removeClass("current").attr("aria-expanded","false");var t=e.find("> ul li");t.length&&(t.removeClass("current").attr("aria-expanded","false"),e.toggleClass("current").attr("aria-expanded",(function(n,e){return"true"==e?"false":"true"})))}},"undefined"!=typeof window&&(window.SphinxRtdTheme={Navigation:n.exports.ThemeNav,StickyNav:n.exports.ThemeNav}),function(){for(var n=0,e=["ms","moz","webkit","o"],t=0;t<e.length&&!window.requestAnimationFrame;++t)window.requestAnimationFrame=window[e[t]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[e[t]+"CancelAnimationFrame"]||window[e[t]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(e,t){var i=(new Date).getTime(),o=Math.max(0,16-(i-n)),r=window.setTimeout((function(){e(i+o)}),o);return n=i+o,r}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(n){clearTimeout(n)})}()}).call(window)},function(n,e){n.exports=jQuery},function(n,e,t){}]);
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/_build/html/_static/js/theme.js
theme.js
!function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=y.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=y.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),y.elements=c+" "+a,j(b)}function f(a){var b=x[a[v]];return b||(b={},w++,a[v]=w,x[w]=b),b}function g(a,c,d){if(c||(c=b),q)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():u.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||t.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),q)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return y.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(y,b.frag)}function j(a){a||(a=b);var d=f(a);return!y.shivCSS||p||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),q||i(a,d),a}function k(a){for(var b,c=a.getElementsByTagName("*"),e=c.length,f=RegExp("^(?:"+d().join("|")+")$","i"),g=[];e--;)b=c[e],f.test(b.nodeName)&&g.push(b.applyElement(l(b)));return g}function l(a){for(var b,c=a.attributes,d=c.length,e=a.ownerDocument.createElement(A+":"+a.nodeName);d--;)b=c[d],b.specified&&e.setAttribute(b.nodeName,b.nodeValue);return e.style.cssText=a.style.cssText,e}function m(a){for(var b,c=a.split("{"),e=c.length,f=RegExp("(^|[\\s,>+~])("+d().join("|")+")(?=[[\\s,>+~#.:]|$)","gi"),g="$1"+A+"\\:$2";e--;)b=c[e]=c[e].split("}"),b[b.length-1]=b[b.length-1].replace(f,g),c[e]=b.join("}");return c.join("{")}function n(a){for(var b=a.length;b--;)a[b].removeNode()}function o(a){function b(){clearTimeout(g._removeSheetTimer),d&&d.removeNode(!0),d=null}var d,e,g=f(a),h=a.namespaces,i=a.parentWindow;return!B||a.printShived?a:("undefined"==typeof h[A]&&h.add(A),i.attachEvent("onbeforeprint",function(){b();for(var f,g,h,i=a.styleSheets,j=[],l=i.length,n=Array(l);l--;)n[l]=i[l];for(;h=n.pop();)if(!h.disabled&&z.test(h.media)){try{f=h.imports,g=f.length}catch(o){g=0}for(l=0;g>l;l++)n.push(f[l]);try{j.push(h.cssText)}catch(o){}}j=m(j.reverse().join("")),e=k(a),d=c(a,j)}),i.attachEvent("onafterprint",function(){n(e),clearTimeout(g._removeSheetTimer),g._removeSheetTimer=setTimeout(b,500)}),a.printShived=!0,a)}var p,q,r="3.7.3",s=a.html5||{},t=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,u=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,v="_html5shiv",w=0,x={};!function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",p="hidden"in a,q=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){p=!0,q=!0}}();var y={elements:s.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:r,shivCSS:s.shivCSS!==!1,supportsUnknownElements:q,shivMethods:s.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=y,j(b);var z=/^$|\b(?:all|print)\b/,A="html5shiv",B=!q&&function(){var c=b.documentElement;return!("undefined"==typeof b.namespaces||"undefined"==typeof b.parentWindow||"undefined"==typeof c.applyElement||"undefined"==typeof c.removeNode||"undefined"==typeof a.attachEvent)}();y.type+=" print",y.shivPrint=o,o(b),"object"==typeof module&&module.exports&&(module.exports=y)}("undefined"!=typeof window?window:this,document);
Appium-Python-Client
/Appium-Python-Client-2.11.1.tar.gz/Appium-Python-Client-2.11.1/docs/_build/html/_static/js/html5shiv-printshiv.min.js
html5shiv-printshiv.min.js