id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
3,300
AirSage/Petrel
petrel/petrel/rdebug.py
petrel.rdebug.NamedPipe
class NamedPipe(object): def __init__(self, name, end=0, mode=0o666): """Open a pair of pipes, name.in and name.out for communication with another process. One process should pass 1 for end, and the other 0. Data is marshalled with pickle.""" self.in_name, self.out_name = name +'.in', name +'.out', try: os.mkfifo(self.in_name,mode) except OSError: pass try: os.mkfifo(self.out_name,mode) except OSError: pass # NOTE: The order the ends are opened in is important - both ends # of pipe 1 must be opened before the second pipe can be opened. if end: self.inp = open(self.out_name,'r') self.out = open(self.in_name,'w') else: self.out = open(self.out_name,'w') self.inp = open(self.in_name,'r') self._open = True def is_open(self): return not (self.inp.closed or self.out.closed) def put(self,msg): if self.is_open(): data = cPickle.dumps(msg,1) self.out.write("%d\n" % len(data)) self.out.write(data) self.out.flush() else: raise Exception("Pipe closed") def get(self): txt=self.inp.readline() if not txt: self.inp.close() else: l = int(txt) data=self.inp.read(l) if len(data) < l: self.inp.close() return cPickle.loads(data) # Convert back to python object. def close(self): self.inp.close() self.out.close() try: os.remove(self.in_name) except OSError: pass try: os.remove(self.out_name) except OSError: pass def __del__(self): self.close()
class NamedPipe(object): def __init__(self, name, end=0, mode=0o666): '''Open a pair of pipes, name.in and name.out for communication with another process. One process should pass 1 for end, and the other 0. Data is marshalled with pickle.''' pass def is_open(self): pass def put(self,msg): pass def get(self): pass def close(self): pass def __del__(self): pass
7
1
8
0
7
1
2
0.14
1
3
0
0
6
5
6
6
53
6
42
15
35
6
48
15
41
4
1
2
14
3,301
AirSage/Petrel
petrel/petrel/emitter.py
petrel.emitter.Bolt
class Bolt(EmitterBase, storm.Bolt): __metaclass__ = ABCMeta
class Bolt(EmitterBase, storm.Bolt): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
3
2
0
2
2
1
0
2
2
1
0
2
0
0
3,302
AirSage/Petrel
samples/wordcount/wordcount.py
wordcount.WordCountBolt
class WordCountBolt(BasicBolt): def __init__(self): super(WordCountBolt, self).__init__(script='wordcount.py') self._count = defaultdict(int) @classmethod def declareOutputFields(cls): return ['word', 'count'] def process(self, tup): log.debug('WordCountBolt.process() called with: %s', tup) word = tup.values[0] self._count[word] += 1 log.debug('WordCountBolt.process() emitting: %s', [word, self._count[word]]) storm.emit([word, self._count[word]])
class WordCountBolt(BasicBolt): def __init__(self): pass @classmethod def declareOutputFields(cls): pass def process(self, tup): pass
5
0
4
0
4
0
1
0
1
2
0
0
2
1
3
6
15
2
13
7
8
0
12
6
8
1
3
0
3
3,303
AirSage/Petrel
samples/wordcount/splitsentence.py
splitsentence.SplitSentenceBolt
class SplitSentenceBolt(BasicBolt): def __init__(self): super(SplitSentenceBolt, self).__init__(script=__file__) def declareOutputFields(self): return ['word'] def process(self, tup): log.debug('SplitSentenceBolt.process() called with: %s', tup) words = tup.values[0].split(" ") for word in words: log.debug('SplitSentenceBolt.process() emitting: %s', word) storm.emit([word])
class SplitSentenceBolt(BasicBolt): def __init__(self): pass def declareOutputFields(self): pass def process(self, tup): pass
4
0
3
0
3
0
1
0
1
1
0
0
3
0
3
6
13
2
11
6
7
0
11
6
7
2
3
1
4
3,304
AirSage/Petrel
samples/wordcount/randomsentence.py
randomsentence.RandomSentenceSpout
class RandomSentenceSpout(Spout): def __init__(self): super(RandomSentenceSpout, self).__init__(script=__file__) #self._index = 0 @classmethod def declareOutputFields(cls): return ['sentence'] sentences = [ "the cow jumped over the moon", "an apple a day keeps the doctor away", "four score and seven years ago", "snow white and the seven dwarfs", "i am at two with nature" ] def nextTuple(self): #if self._index == len(self.sentences): # # This is just a demo; keep sleeping and returning None after we run # # out of data. We can't just sleep forever or Storm will hang. # time.sleep(1) # return None time.sleep(0.25); sentence = self.sentences[random.randint(0, len(self.sentences) - 1)] #sentence = self.sentences[self._index] #self._index += 1 log.debug('randomsentence emitting: %s', sentence) storm.emit([sentence])
class RandomSentenceSpout(Spout): def __init__(self): pass @classmethod def declareOutputFields(cls): pass def nextTuple(self): pass
5
0
6
0
3
2
1
0.44
1
1
0
0
2
0
3
6
30
4
18
7
13
8
11
6
7
1
3
0
3
3,305
AirSage/Petrel
petrel/petrel/topologybuilder.py
petrel.topologybuilder._BoltGetter
class _BoltGetter(object): def __init__(self, owner, boltId): self._owner = owner self._boltId = boltId def allGrouping(self, componentId, streamId='default'): return self.grouping(componentId, 'all', NullStruct(), streamId) def fieldsGrouping(self, componentId, fields, streamId='default'): return self.grouping(componentId, 'fields', fields, streamId) def globalGrouping(self, componentId, streamId='default'): return self.fieldsGrouping(componentId, [], streamId) def shuffleGrouping(self, componentId, streamId='default'): return self.grouping(componentId, 'shuffle', NullStruct(), streamId) def localOrShuffleGrouping(self, componentId, streamId='default'): return self.grouping(componentId, 'local_or_shuffle', NullStruct(), streamId) def noneGrouping(self, componentId, streamId='default'): return self.grouping(componentId, 'none', NullStruct(), streamId) def directGrouping(self, componentId, streamId='default'): return self.grouping(componentId, 'direct', NullStruct(), streamId) def grouping(self, componentId, attr, grouping, streamId): o_grouping = Grouping() setattr(o_grouping, attr, grouping) self._owner._commons[self._boltId].inputs[GlobalStreamId(componentId, streamId)] = o_grouping return self
class _BoltGetter(object): def __init__(self, owner, boltId): pass def allGrouping(self, componentId, streamId='default'): pass def fieldsGrouping(self, componentId, fields, streamId='default'): pass def globalGrouping(self, componentId, streamId='default'): pass def shuffleGrouping(self, componentId, streamId='default'): pass def localOrShuffleGrouping(self, componentId, streamId='default'): pass def noneGrouping(self, componentId, streamId='default'): pass def directGrouping(self, componentId, streamId='default'): pass def grouping(self, componentId, attr, grouping, streamId): pass
10
0
2
0
2
0
1
0
1
0
0
0
9
2
9
9
31
8
23
13
13
0
23
13
13
1
1
0
9
3,306
AirSage/Petrel
petrel/petrel/topologybuilder.py
petrel.topologybuilder.TopologyBuilder
class TopologyBuilder(object): def __init__(self): self._bolts = {} self._spouts = {} self._commons = {} #/** # * Define a new bolt in this topology with the specified amount of parallelism. # * # * @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs. # * @param bolt the bolt # * @param parallelism_hint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process somewhere around the cluster. # * @return use the returned object to declare the inputs to this component # */ def setBolt(self, id, bolt, parallelism_hint=None): self._validateUnusedId(id); self._initCommon(id, bolt, parallelism_hint); self._bolts[id] = bolt return _BoltGetter(self, id) #/** # * Define a new spout in this topology. # * # * @param id the id of this component. This id is referenced by other components that want to consume this spout's outputs. # * @param spout the spout # */ def setSpout(self, id, spout, parallelism_hint=None): self._validateUnusedId(id); self._initCommon(id, spout, parallelism_hint) self._spouts[id] = spout def addOutputStream(self, id, streamId, output_fields, direct=False): self._commons[id].streams[streamId] = StreamInfo(output_fields, direct=direct) def createTopology(self): boltSpecs = {} spoutSpecs = {} for boltId, bolt in six.iteritems(self._bolts): t_bolt = Bolt() shell_object = ShellComponent() shell_object.execution_command = bolt.execution_command shell_object.script = bolt.script t_bolt.bolt_object = ComponentObject() t_bolt.bolt_object.shell = shell_object t_bolt.common = self._getComponentCommon(boltId, bolt) boltSpecs[boltId] = t_bolt for spoutId, spout in six.iteritems(self._spouts): spout_spec = SpoutSpec() shell_object = ShellComponent() shell_object.execution_command = spout.execution_command shell_object.script = spout.script spout_spec.spout_object = ComponentObject() spout_spec.spout_object.shell = shell_object spout_spec.common = self._getComponentCommon(spoutId, spout) spoutSpecs[spoutId] = spout_spec topology = StormTopology() topology.spouts = spoutSpecs topology.bolts = boltSpecs topology.state_spouts = {} # Not supported yet, I think return topology def write(self, stream): """Writes the topology to a stream or file.""" topology = self.createTopology() def write_it(stream): transportOut = TMemoryBuffer() protocolOut = TBinaryProtocol.TBinaryProtocol(transportOut) topology.write(protocolOut) bytes = transportOut.getvalue() stream.write(bytes) if isinstance(stream, six.string_types): with open(stream, 'wb') as f: write_it(f) else: write_it(stream) return topology def read(self, stream): """Reads the topology from a stream or file.""" def read_it(stream): bytes = stream.read() transportIn = TMemoryBuffer(bytes) protocolIn = TBinaryProtocol.TBinaryProtocol(transportIn) topology = StormTopology() topology.read(protocolIn) return topology if isinstance(stream, six.string_types): with open(stream, 'rb') as f: return read_it(f) else: return read_it(stream) def _validateUnusedId(self, id): if id in self._bolts: raise KeyError("Bolt has already been declared for id " + id); elif id in self._spouts: raise KeyError("Spout has already been declared for id " + id); def _getComponentCommon(self, id, component): common = self._commons[id] stream_info = StreamInfo() stream_info.output_fields = component.declareOutputFields() stream_info.direct = False # Appears to be unused by Storm common.streams['default'] = stream_info return common def _initCommon(self, id, component, parallelism): common = ComponentCommon() common.inputs = {} common.streams = {} if parallelism is not None: common.parallelism_hint = parallelism conf = component.getComponentConfiguration() if conf is not None: common.json_conf = json.dumps(conf) self._commons[id] = common
class TopologyBuilder(object): def __init__(self): pass def setBolt(self, id, bolt, parallelism_hint=None): pass def setSpout(self, id, spout, parallelism_hint=None): pass def addOutputStream(self, id, streamId, output_fields, direct=False): pass def createTopology(self): pass def write(self, stream): '''Writes the topology to a stream or file.''' pass def write_it(stream): pass def read(self, stream): '''Reads the topology from a stream or file.''' pass def read_it(stream): pass def _validateUnusedId(self, id): pass def _getComponentCommon(self, id, component): pass def _initCommon(self, id, component, parallelism): pass
13
2
9
1
9
0
2
0.2
1
3
2
0
10
3
10
10
124
17
91
38
78
18
88
36
75
3
1
2
20
3,307
AirSage/Petrel
petrel/petrel/topologybuilder.py
petrel.topologybuilder.TMemoryBuffer
class TMemoryBuffer(TTransport.TMemoryBuffer): """ This class is a workaround for a Python 3 incompatibility in thrift -- its implementation of TMemoryBuffer uses a StringIO object, but it should use bytes. """ def __init__(self, value=None): """value -- a value to read from for stringio If value is set, this will be a transport for reading, otherwise, it is for writing""" if value is not None: self._buffer = io.BytesIO(value) else: self._buffer = io.BytesIO() def write(self, buf): if six.PY3: if not isinstance(buf, six.binary_type): buf = six.binary_type(buf, 'ascii') self._buffer.write(buf)
class TMemoryBuffer(TTransport.TMemoryBuffer): ''' This class is a workaround for a Python 3 incompatibility in thrift -- its implementation of TMemoryBuffer uses a StringIO object, but it should use bytes. ''' def __init__(self, value=None): '''value -- a value to read from for stringio If value is set, this will be a transport for reading, otherwise, it is for writing''' pass def write(self, buf): pass
3
2
7
1
5
2
3
0.73
1
0
0
0
2
1
2
2
21
2
11
4
8
8
10
4
7
3
1
2
5
3,308
AirSage/Petrel
petrel/petrel/tests/test_topology.py
petrel.tests.test_topology.WordCount
class WordCount(BasicBolt): def __init__(self, execution_command=None): super(WordCount, self).__init__(script='wordcount.py') def declareOutputFields(self): return ['word', 'count']
class WordCount(BasicBolt): def __init__(self, execution_command=None): pass def declareOutputFields(self): pass
3
0
2
0
2
0
1
0
1
1
0
0
2
0
2
5
6
1
5
3
2
0
5
3
2
1
3
0
2
3,309
AirSage/Petrel
petrel/petrel/tests/test_topology.py
petrel.tests.test_topology.TestTopology
class TestTopology(unittest.TestCase): def test1(self): # Build a topology builder = TopologyBuilder() builder.setSpout("spout", RandomSentenceSpout(), 5) builder.setBolt("split", SplitSentence(), 8).shuffleGrouping("spout") builder.setBolt("count", WordCount(), 12).fieldsGrouping("split", ["word"]) # Save the topology. io_out = StringIO() builder.write(io_out) # Read the topology. io_in = StringIO(io_out.getvalue()) topology = builder.read(io_in) # Verify the topology settings were saved and loaded correctly. self.assertEqual(['spout'], topology.spouts.keys()) self.assertEqual(['count', 'split'], sorted(topology.bolts.keys())) spout = topology.spouts['spout'] self.assertEqual('python2.7', spout.spout_object.shell.execution_command) self.assertEqual('randomsentence.py', spout.spout_object.shell.script) self.assertEqual(['default'], sorted(spout.common.streams.keys())) self.assertEqual(['sentence'], spout.common.streams['default'].output_fields) self.assertEqual(False, spout.common.streams['default'].direct) bolt = topology.bolts['split'] self.assertEqual('python2.7', bolt.bolt_object.shell.execution_command) self.assertEqual('splitsentence.py', bolt.bolt_object.shell.script) self.assertEqual(['default'], sorted(bolt.common.streams.keys())) self.assertEqual(['word'], bolt.common.streams['default'].output_fields) self.assertEqual(False, bolt.common.streams['default'].direct) bolt = topology.bolts['count'] self.assertEqual('python2.7', bolt.bolt_object.shell.execution_command) self.assertEqual('wordcount.py', bolt.bolt_object.shell.script) self.assertEqual(['default'], sorted(bolt.common.streams.keys())) self.assertEqual(['word', 'count'], bolt.common.streams['default'].output_fields) self.assertEqual(False, bolt.common.streams['default'].direct)
class TestTopology(unittest.TestCase): def test1(self): pass
2
0
39
6
29
4
1
0.13
1
4
4
0
1
0
1
73
40
6
30
8
28
4
30
8
28
1
2
0
1
3,310
AirSage/Petrel
petrel/petrel/tests/test_topology.py
petrel.tests.test_topology.SplitSentence
class SplitSentence(BasicBolt): def __init__(self, execution_command=None): super(SplitSentence, self).__init__(script='splitsentence.py') def declareOutputFields(self): return ['word']
class SplitSentence(BasicBolt): def __init__(self, execution_command=None): pass def declareOutputFields(self): pass
3
0
2
0
2
0
1
0
1
1
0
0
2
0
2
5
6
1
5
3
2
0
5
3
2
1
3
0
2
3,311
AirSage/Petrel
petrel/petrel/tests/test_topology.py
petrel.tests.test_topology.RandomSentenceSpout
class RandomSentenceSpout(Spout): def __init__(self, execution_command=None): super(RandomSentenceSpout, self).__init__(script='randomsentence.py') def declareOutputFields(self): return ['sentence']
class RandomSentenceSpout(Spout): def __init__(self, execution_command=None): pass def declareOutputFields(self): pass
3
0
2
0
2
0
1
0
1
1
0
0
2
0
2
5
6
1
5
3
2
0
5
3
2
1
3
0
2
3,312
AirSage/Petrel
petrel/petrel/storm.py
petrel.storm.Tuple
class Tuple(object): __slots__ = ['id', 'component', 'stream', 'task', 'values'] def __init__(self, id, component, stream, task, values): self.id = id self.component = component self.stream = stream self.task = task self.values = values def __eq__(self, other): if not isinstance(other, Tuple): return False for k in self.__slots__: if getattr(self, k) != getattr(other, k): return False return True def __ne__(self, other): return not (self == other) def __repr__(self): return '<%s%s>' % ( self.__class__.__name__, ''.join(' %s=%r' % (k, getattr(self, k)) for k in sorted(self.__slots__))) def is_heartbeat_tuple(self): return self.task == -1 and self.stream == "__heartbeat" def is_tick_tuple(self): return self.task == -1 and self.stream == "__tick"
class Tuple(object): def __init__(self, id, component, stream, task, values): pass def __eq__(self, other): pass def __ne__(self, other): pass def __repr__(self): pass def is_heartbeat_tuple(self): pass def is_tick_tuple(self): pass
7
0
4
0
4
0
2
0
1
0
0
0
6
5
6
6
32
7
25
14
18
0
23
14
16
4
1
2
9
3,313
AirSage/Petrel
petrel/petrel/storm.py
petrel.storm.Spout
class Spout(Task): def initialize(self, conf, context): pass def ack(self, id): pass def fail(self, id): pass def nextTuple(self): pass def run(self): global MODE MODE = Spout self.shared_initialize() try: while True: msg = readCommand() command = msg["command"] if command == "next": self.nextTuple() elif command == "ack": self.ack(msg["id"]) elif command == "fail": self.fail(msg["id"]) sync() except Exception as e: self.report_exception('E_SPOUTFAILED', e) storm_log.exception('Caught exception in Spout.run: %s', str(e))
class Spout(Task): def initialize(self, conf, context): pass def ack(self, id): pass def fail(self, id): pass def nextTuple(self): pass def run(self): pass
6
0
5
0
5
0
2
0
1
2
0
1
5
0
5
7
31
4
27
10
20
0
25
9
18
6
2
3
10
3,314
AirSage/Petrel
petrel/petrel/emitter.py
petrel.emitter.BasicBolt
class BasicBolt(EmitterBase, storm.BasicBolt): __metaclass__ = ABCMeta
class BasicBolt(EmitterBase, storm.BasicBolt): pass
1
0
0
0
0
0
0
0
2
0
0
4
0
0
0
3
2
0
2
2
1
0
2
2
1
0
2
0
0
3,315
AirSage/Petrel
petrel/petrel/storm.py
petrel.storm.StormIPCException
class StormIPCException(Exception): pass
class StormIPCException(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
3,316
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_report.py
tests.test_report.TestReport
class TestReport(unittest.TestCase): LOG_DIR = DIR(DEFAULT_LOG_DIR) OUTPUT_HTML = HTML_FILE EXPORT_DIR = DIR("export") HTTP_STATIC = "http://init.nie.netease.com/moa/new_report" SCRIPT_NAME = os.path.basename(OWL).replace(".air", "") @classmethod def setUpClass(cls): if not ADB().devices(state="device"): raise RuntimeError("At lease one adb device required") cls.delete_path([cls.OUTPUT_HTML, cls.EXPORT_DIR, cls.LOG_DIR]) @classmethod def tearDownClass(cls): cls.delete_path([cls.OUTPUT_HTML, cls.EXPORT_DIR, cls.LOG_DIR]) def setUp(self): self.delete_path([self.OUTPUT_HTML, self.EXPORT_DIR]) if not os.path.exists(self.LOG_DIR): argv = ["run", OWL, "--device", "Android:///", "--log", self.LOG_DIR, "--recording"] main_parser(argv) def tearDown(self): self.delete_path([self.OUTPUT_HTML, self.EXPORT_DIR]) @classmethod def delete_path(cls, path_list): for path in path_list: try_remove(path) def test_logtohtml_default(self): # All parameters use default parameters rpt = LogToHtml(OWL) rpt.report() self.assertTrue(os.path.exists(self.OUTPUT_HTML)) def test_logtohtml_set_log(self): # set log_root rpt_logroot = LogToHtml(OWL, log_root=self.LOG_DIR) rpt_logroot.report() self.assertTrue(os.path.exists(self.OUTPUT_HTML)) def test_logtohtml_script_py(self): # script_root is .py script_py = os.path.join(OWL, self.SCRIPT_NAME + ".py") rpt_py = LogToHtml(script_py) rpt_py.report() self.assertTrue(os.path.exists(self.OUTPUT_HTML)) def test_set_logdir(self): new_logfile = "log123.txt" new_logdir = DIR("./logs_new") self.delete_path([new_logdir, new_logfile]) # set logfile = ./logs_new/log123.txt ST.LOG_FILE = new_logfile set_logdir(new_logdir) argv = ["run", OWL, "--device", "Android:///"] main_parser(argv) G.LOGGER.set_logfile(None) self.assertTrue(os.path.exists(os.path.join(ST.LOG_DIR, ST.LOG_FILE))) rpt = LogToHtml(OWL) rpt.report() self.assertTrue(os.path.exists(self.OUTPUT_HTML)) # test export log self.delete_path([self.EXPORT_DIR]) rpt_export = LogToHtml(OWL, export_dir=self.EXPORT_DIR) rpt_export.report() export_path = os.path.join(self.EXPORT_DIR, self.SCRIPT_NAME + ".log") self.assertTrue(os.path.exists(os.path.join(export_path, self.OUTPUT_HTML))) self.assertTrue(os.path.exists(os.path.join(export_path, "static"))) self.delete_path([new_logdir, new_logfile]) ST.LOG_FILE = DEFAULT_LOG_FILE ST.LOG_DIR = DEFAULT_LOG_DIR def test_cli(self): argv = ["report", OWL, "--log_root", self.LOG_DIR, "--outfile", self.OUTPUT_HTML] main_parser(argv) self.assertTrue(os.path.exists(self.OUTPUT_HTML)) def test_static_root_cli(self): argv = ["report", OWL, "--log_root", self.LOG_DIR, "--outfile", self.OUTPUT_HTML, "--static_root", self.HTTP_STATIC] main_parser(argv) self.assertTrue(os.path.exists(self.OUTPUT_HTML)) with open(self.OUTPUT_HTML, encoding="utf-8", errors="ignore") as f: self.assertTrue(self.HTTP_STATIC in f.read()) def test_static_root(self): # set static_root rpt = LogToHtml(OWL, self.LOG_DIR, static_root=self.HTTP_STATIC) rpt.report() self.assertTrue(os.path.exists(self.OUTPUT_HTML)) with open(self.OUTPUT_HTML, encoding="utf-8", errors="ignore") as f: self.assertTrue(self.HTTP_STATIC in f.read()) def test_output_file(self): rpt = LogToHtml(OWL) new_output_file = os.path.join(self.LOG_DIR, "new_log.html") rpt.report(output_file=new_output_file) self.assertTrue(os.path.exists(new_output_file)) self.delete_path([new_output_file]) def test_export_log(self): rpt = LogToHtml(OWL, export_dir=self.EXPORT_DIR) rpt.report() export_path = os.path.join(self.EXPORT_DIR, self.SCRIPT_NAME + ".log") self.assertTrue(os.path.exists(os.path.join(export_path, self.OUTPUT_HTML))) self.assertTrue(os.path.exists(os.path.join(export_path, "static"))) def test_export_log_http_static(self): # http static file rpt_static = LogToHtml(OWL, export_dir=self.EXPORT_DIR, static_root=self.HTTP_STATIC) rpt_static.report() export_path = os.path.join(self.EXPORT_DIR, self.SCRIPT_NAME + ".log") self.assertTrue(os.path.exists(os.path.join(export_path, self.OUTPUT_HTML))) self.assertTrue(not os.path.exists(os.path.join(export_path, "static"))) def test_simple_report(self): simple_report(OWL) self.assertTrue(os.path.exists(self.OUTPUT_HTML))
class TestReport(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUpClass(cls): pass def tearDownClass(cls): pass @classmethod def delete_path(cls, path_list): pass def test_logtohtml_default(self): pass def test_logtohtml_set_log(self): pass def test_logtohtml_script_py(self): pass def test_set_logdir(self): pass def test_cli(self): pass def test_static_root_cli(self): pass def test_static_root_cli(self): pass def test_output_file(self): pass def test_export_log(self): pass def test_export_log_http_static(self): pass def test_simple_report(self): pass
20
0
6
0
6
0
1
0.07
1
5
4
0
13
0
16
88
125
20
98
48
78
7
94
43
77
2
2
1
19
3,317
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/keypoint_matching_contrib.py
airtest.aircv.keypoint_matching_contrib.SURFMatching
class SURFMatching(KeypointMatching): """SURF Matching.""" METHOD_NAME = "SURF" # 日志中的方法名 # 是否检测方向不变性:0检测/1不检测 UPRIGHT = 0 # SURF算子的Hessian Threshold HESSIAN_THRESHOLD = 400 # SURF识别特征点匹配方法设置: FLANN_INDEX_KDTREE = 0 def init_detector(self): """Init keypoint detector object.""" # BRIEF is a feature descriptor, recommand CenSurE as a fast detector: if check_cv_version_is_new(): # OpenCV3/4, surf is in contrib module, you need to compile it seperately. try: self.detector = cv2.xfeatures2d.SURF_create(self.HESSIAN_THRESHOLD, upright=self.UPRIGHT) except: raise NoModuleError("There is no %s module in your OpenCV environment, need contribmodule!" % self.METHOD_NAME) else: # OpenCV2.x self.detector = cv2.SURF(self.HESSIAN_THRESHOLD, upright=self.UPRIGHT) # # create FlnnMatcher object: self.matcher = cv2.FlannBasedMatcher({'algorithm': self.FLANN_INDEX_KDTREE, 'trees': 5}, dict(checks=50)) def get_keypoints_and_descriptors(self, image): """获取图像特征点和描述符.""" keypoints, descriptors = self.detector.detectAndCompute(image, None) return keypoints, descriptors def match_keypoints(self, des_sch, des_src): """Match descriptors (特征值匹配).""" # 匹配两个图片中的特征点集,k=2表示每个特征点取出2个最匹配的对应点: return self.matcher.knnMatch(des_sch, des_src, k=2)
class SURFMatching(KeypointMatching): '''SURF Matching.''' def init_detector(self): '''Init keypoint detector object.''' pass def get_keypoints_and_descriptors(self, image): '''获取图像特征点和描述符.''' pass def match_keypoints(self, des_sch, des_src): '''Match descriptors (特征值匹配).''' pass
4
4
8
0
5
3
2
0.68
1
2
1
0
3
2
3
19
37
6
19
11
15
13
18
11
14
3
2
2
5
3,318
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/multiscale_template_matching.py
airtest.aircv.multiscale_template_matching.MultiScaleTemplateMatchingPre
class MultiScaleTemplateMatchingPre(MultiScaleTemplateMatching): """基于截图预设条件的多尺度模板匹配.""" METHOD_NAME = "MSTemplatePre" DEVIATION = 150 @print_run_time def find_best_result(self): """函数功能:找到最优结果.""" if self.resolution!=(): # 第一步:校验图像输入 check_source_larger_than_search(self.im_source, self.im_search) if self.resolution[0]<self.im_search.shape[1] or self.resolution[1]<self.im_search.shape[0]: raise TemplateInputError("error: resolution is too small.") # 第二步:计算模板匹配的结果矩阵res if not self.record_pos is None: area, self.resolution = self._get_area_scope(self.im_source, self.im_search, self.record_pos, self.resolution) self.im_source = aircv.crop_image(self.im_source, area) check_source_larger_than_search(self.im_source, self.im_search) r_min, r_max = self._get_ratio_scope( self.im_source, self.im_search, self.resolution) s_gray, i_gray = img_mat_rgb_2_gray(self.im_search), img_mat_rgb_2_gray(self.im_source) confidence, max_loc, w, h, _ = self.multi_scale_search( i_gray, s_gray, ratio_min=r_min, ratio_max=r_max, step=self.scale_step, threshold=self.threshold, time_out=1.0) if not self.record_pos is None: max_loc = (max_loc[0] + area[0], max_loc[1] + area[1]) # 求取识别位置: 目标中心 + 目标区域: middle_point, rectangle = self._get_target_rectangle(max_loc, w, h) best_match = generate_result(middle_point, rectangle, confidence) LOGGING.debug("[%s] threshold=%s, result=%s" % (self.METHOD_NAME, self.threshold, best_match)) return best_match if confidence >= self.threshold else None else: return None def _get_ratio_scope(self, src, templ, resolution): """预测缩放比的上下限.""" H, W = src.shape[0], src.shape[1] th, tw = templ.shape[0], templ.shape[1] w, h = resolution rmin = min(H/h, W/w) # 新旧模板比下限 rmax = max(H/h, W/w) # 新旧模板比上限 ratio = max(th/H, tw/W) # 小图大图比 r_min = ratio*rmin r_max = ratio*rmax return max(r_min, self.scale_step), min(r_max, 0.99) def get_predict_point(self, record_pos, screen_resolution): """预测缩放后的点击位置点.""" delta_x, delta_y = record_pos _w, _h = screen_resolution target_x = delta_x * _w + _w * 0.5 target_y = delta_y * _w + _h * 0.5 return target_x, target_y def _get_area_scope(self, src, templ, record_pos, resolution): """预测搜索区域.""" H, W = src.shape[0], src.shape[1] th, tw = templ.shape[0], templ.shape[1] w, h = resolution x, y = self.get_predict_point(record_pos, (W, H)) predict_x_radius = max(int(tw * W / (w)), self.DEVIATION) predict_y_radius = max(int(th * H / (h)), self.DEVIATION) area = ( max(x - predict_x_radius, 0), max(y - predict_y_radius, 0), min(x + predict_x_radius, W), min(y + predict_y_radius, H), ) return area, (w*(area[3]-area[1])/W, h*(area[2]-area[0])/H)
class MultiScaleTemplateMatchingPre(MultiScaleTemplateMatching): '''基于截图预设条件的多尺度模板匹配.''' @print_run_time def find_best_result(self): '''函数功能:找到最优结果.''' pass def _get_ratio_scope(self, src, templ, resolution): '''预测缩放比的上下限.''' pass def get_predict_point(self, record_pos, screen_resolution): '''预测缩放后的点击位置点.''' pass def _get_area_scope(self, src, templ, record_pos, resolution): '''预测搜索区域.''' pass
6
5
16
1
14
3
2
0.19
1
2
1
0
4
4
4
12
73
7
58
36
52
11
47
33
42
6
2
2
9
3,319
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/screen_recorder.py
airtest.aircv.screen_recorder.FfmpegVidWriter
class FfmpegVidWriter: """ Generate a video using FFMPEG. """ def __init__(self, outfile, width, height, fps=10, orientation=0): self.fps = fps # 三种横竖屏录屏模式 1 竖屏 2 横屏 0 方形居中 self.orientation = RECORDER_ORI.get(str(orientation).upper(), orientation) if self.orientation == 1: self.height = max(width, height) self.width = min(width, height) elif self.orientation == 2: self.width = max(width, height) self.height = min(width, height) else: self.width = self.height = max(width, height) # 满足视频宽高条件 self.height = height = self.height - (self.height % 32) + 32 self.width = width = self.width - (self.width % 32) + 32 self.cache_frame = np.zeros((height, width, 3), dtype=np.uint8) try: subprocess.Popen("ffmpeg", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).wait() except FileNotFoundError: from airtest.utils.ffmpeg import ffmpeg_setter try: ffmpeg_setter.add_paths() except Exception as e: print("Error: setting ffmpeg path failed, please download it at https://ffmpeg.org/download.html then add ffmpeg path to PATH") raise self.process = ( ffmpeg .input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height), framerate=self.fps) .output(outfile, pix_fmt='yuv420p', vcodec='libx264', crf=25, preset="veryfast", framerate=self.fps) .global_args("-loglevel", "error") .overwrite_output() .run_async(pipe_stdin=True) ) self.writer = self.process.stdin def process_frame(self, frame): assert len(frame.shape) == 3 frame = frame[..., ::-1] if self.orientation == 1 and frame.shape[1] > frame.shape[0]: frame = cv2.resize(frame, (self.width, int(self.width*self.width/self.height))) elif self.orientation == 2 and frame.shape[1] < frame.shape[0]: frame = cv2.resize(frame, (int(self.height*self.height/self.width), self.height)) h_st = max(self.cache_frame.shape[0]//2 - frame.shape[0]//2, 0) w_st = max(self.cache_frame.shape[1]//2 - frame.shape[1]//2, 0) h_ed = min(h_st+frame.shape[0], self.cache_frame.shape[0]) w_ed = min(w_st+frame.shape[1], self.cache_frame.shape[1]) self.cache_frame[:] = 0 self.cache_frame[h_st:h_ed, w_st:w_ed, :] = frame[:(h_ed-h_st), :(w_ed-w_st)] return self.cache_frame.copy() def write(self, frame): self.writer.write(frame.astype(np.uint8)) def close(self): try: self.writer.close() self.process.wait(timeout=5) except Exception as e: print(f"Error closing ffmpeg process: {e}") finally: try: self.process.terminate() except Exception as e: print(f"Error terminating ffmpeg process: {e}")
class FfmpegVidWriter: ''' Generate a video using FFMPEG. ''' def __init__(self, outfile, width, height, fps=10, orientation=0): pass def process_frame(self, frame): pass def write(self, frame): pass def close(self): pass
5
1
17
1
15
1
3
0.08
0
5
0
0
4
7
4
4
74
7
62
19
56
5
49
17
43
5
0
2
12
3,320
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/screen_recorder.py
airtest.aircv.screen_recorder.ScreenRecorder
class ScreenRecorder: def __init__(self, outfile, get_frame_func, fps=10, snapshot_sleep=0.001, orientation=0): self.get_frame_func = get_frame_func self.tmp_frame = self.get_frame_func() self.snapshot_sleep = snapshot_sleep width, height = self.tmp_frame.shape[1], self.tmp_frame.shape[0] self.writer = FfmpegVidWriter(outfile, width, height, fps, orientation) self.tmp_frame = self.writer.process_frame(self.tmp_frame) self._is_running = False self._stop_flag = False self._stop_time = 0 def is_running(self): return self._is_running @property def stop_time(self): return self._stop_time @stop_time.setter def stop_time(self, max_time): if isinstance(max_time, int) and max_time > 0: self._stop_time = time.time() + max_time else: print("failed to set stop time") def is_stop(self): if self._stop_flag: return True if self._stop_time > 0 and time.time() >= self._stop_time: return True return False def start(self): if self._is_running: print("recording is already running, please don't call again") return False self._is_running = True self.t_stream = threading.Thread(target=self.get_frame_loop) self.t_stream.setDaemon(True) self.t_stream.start() self.t_write = threading.Thread(target=self.write_frame_loop) self.t_write.setDaemon(True) self.t_write.start() return True def stop(self): self._is_running = False self._stop_flag = True self.t_write.join() self.t_stream.join() self.writer.close() # Ensure writer is closed def get_frame_loop(self): # 单独一个线程持续截图 try: while True: tmp_frame = self.get_frame_func() self.tmp_frame = self.writer.process_frame(tmp_frame) time.sleep(self.snapshot_sleep) if self.is_stop(): break self._stop_flag = True except Exception as e: print("record thread error", e) self._stop_flag = True raise def write_frame_loop(self): try: duration = 1.0/self.writer.fps last_time = time.time() self._stop_flag = False while True: if time.time()-last_time >= duration: last_time += duration try: self.writer.write(self.tmp_frame) except Exception as e: print(f"Error writing frame: {e}") break if self.is_stop(): break time.sleep(0.0001) self.writer.close() self._stop_flag = True except Exception as e: print("write thread error", e) self._stop_flag = True self.writer.close() # Ensure the writer is closed on error raise
class ScreenRecorder: def __init__(self, outfile, get_frame_func, fps=10, snapshot_sleep=0.001, orientation=0): pass def is_running(self): pass @property def stop_time(self): pass @stop_time.setter def stop_time(self): pass def is_stop(self): pass def start(self): pass def stop_time(self): pass def get_frame_loop(self): pass def write_frame_loop(self): pass
12
0
9
0
9
0
2
0.04
0
4
1
0
9
9
9
9
93
10
82
27
70
3
79
23
69
6
0
4
21
3,321
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/template_matching.py
airtest.aircv.template_matching.TemplateMatching
class TemplateMatching(object): """模板匹配.""" METHOD_NAME = "Template" MAX_RESULT_COUNT = 10 def __init__(self, im_search, im_source, threshold=0.8, rgb=True): super(TemplateMatching, self).__init__() self.im_source = im_source self.im_search = im_search self.threshold = threshold self.rgb = rgb @print_run_time def find_all_results(self): """基于模板匹配查找多个目标区域的方法.""" # 第一步:校验图像输入 check_source_larger_than_search(self.im_source, self.im_search) # 第二步:计算模板匹配的结果矩阵res res = self._get_template_result_matrix() # 第三步:依次获取匹配结果 result = [] h, w = self.im_search.shape[:2] while True: # 本次循环中,取出当前结果矩阵中的最优值 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) # 求取可信度: confidence = self._get_confidence_from_matrix(max_loc, max_val, w, h) if confidence < self.threshold or len(result) > self.MAX_RESULT_COUNT: break # 求取识别位置: 目标中心 + 目标区域: middle_point, rectangle = self._get_target_rectangle(max_loc, w, h) one_good_match = generate_result(middle_point, rectangle, confidence) result.append(one_good_match) # 屏蔽已经取出的最优结果,进入下轮循环继续寻找: # cv2.floodFill(res, None, max_loc, (-1000,), max(max_val, 0), flags=cv2.FLOODFILL_FIXED_RANGE) cv2.rectangle(res, (int(max_loc[0] - w / 2), int(max_loc[1] - h / 2)), (int(max_loc[0] + w / 2), int(max_loc[1] + h / 2)), (0, 0, 0), -1) return result if result else None @print_run_time def find_best_result(self): """基于kaze进行图像识别,只筛选出最优区域.""" """函数功能:找到最优结果.""" # 第一步:校验图像输入 check_source_larger_than_search(self.im_source, self.im_search) # 第二步:计算模板匹配的结果矩阵res res = self._get_template_result_matrix() # 第三步:依次获取匹配结果 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) h, w = self.im_search.shape[:2] # 求取可信度: confidence = self._get_confidence_from_matrix(max_loc, max_val, w, h) # 求取识别位置: 目标中心 + 目标区域: middle_point, rectangle = self._get_target_rectangle(max_loc, w, h) best_match = generate_result(middle_point, rectangle, confidence) LOGGING.debug("[%s] threshold=%s, result=%s" % (self.METHOD_NAME, self.threshold, best_match)) return best_match if confidence >= self.threshold else None def _get_confidence_from_matrix(self, max_loc, max_val, w, h): """根据结果矩阵求出confidence.""" # 求取可信度: if self.rgb: # 如果有颜色校验,对目标区域进行BGR三通道校验: img_crop = self.im_source[max_loc[1]:max_loc[1] + h, max_loc[0]: max_loc[0] + w] confidence = cal_rgb_confidence(img_crop, self.im_search) else: confidence = max_val return confidence def _get_template_result_matrix(self): """求取模板匹配的结果矩阵.""" # 灰度识别: cv2.matchTemplate( )只能处理灰度图片参数 s_gray, i_gray = img_mat_rgb_2_gray(self.im_search), img_mat_rgb_2_gray(self.im_source) return cv2.matchTemplate(i_gray, s_gray, cv2.TM_CCOEFF_NORMED) def _get_target_rectangle(self, left_top_pos, w, h): """根据左上角点和宽高求出目标区域.""" x_min, y_min = left_top_pos # 中心位置的坐标: x_middle, y_middle = int(x_min + w / 2), int(y_min + h / 2) # 左下(min,max)->右下(max,max)->右上(max,min) left_bottom_pos, right_bottom_pos = (x_min, y_min + h), (x_min + w, y_min + h) right_top_pos = (x_min + w, y_min) # 点击位置: middle_point = (x_middle, y_middle) # 识别目标区域: 点序:左上->左下->右下->右上, 左上(min,min)右下(max,max) rectangle = (left_top_pos, left_bottom_pos, right_bottom_pos, right_top_pos) return middle_point, rectangle
class TemplateMatching(object): '''模板匹配.''' def __init__(self, im_search, im_source, threshold=0.8, rgb=True): pass @print_run_time def find_all_results(self): '''基于模板匹配查找多个目标区域的方法.''' pass @print_run_time def find_best_result(self): '''基于kaze进行图像识别,只筛选出最优区域.''' pass def _get_confidence_from_matrix(self, max_loc, max_val, w, h): '''根据结果矩阵求出confidence.''' pass def _get_template_result_matrix(self): '''求取模板匹配的结果矩阵.''' pass def _get_target_rectangle(self, left_top_pos, w, h): '''根据左上角点和宽高求出目标区域.''' pass
9
6
14
2
8
4
2
0.5
1
2
0
0
6
4
6
6
99
18
54
37
45
27
51
35
44
4
1
2
11
3,322
AirtestProject/Airtest
AirtestProject_Airtest/airtest/cli/runner.py
airtest.cli.runner.AirtestCase
class AirtestCase(unittest.TestCase): PROJECT_ROOT = "." SCRIPTEXT = ".air" TPLEXT = ".png" @classmethod def setUpClass(cls): cls.args = args setup_by_args(args) # setup script exec scope cls.scope = copy(globals()) cls.scope["exec_script"] = cls.exec_other_script def setUp(self): if self.args.log and self.args.recording: for dev in G.DEVICE_LIST: try: dev.start_recording() except: traceback.print_exc() # support for if __name__ == '__main__' self.scope['__name__'] = '__main__' def tearDown(self): if self.args.log and self.args.recording: for k, dev in enumerate(G.DEVICE_LIST): # 录屏文件保存的命名规则: # 如果未指定文件名,只传了--recording,就默认用recording_手机序列号.mp4来命名 # 如果指定了文件名--recording test.mp4,且超过一台手机,就命名为 手机序列号_test.mp4 # 否则直接用指定的文件名保存录屏,必须是mp4结尾 try: if isinstance(self.args.recording, six.string_types) and self.args.recording.endswith(".mp4"): basename = os.path.basename(self.args.recording) output_name = dev.serialno + "_" + basename if len(G.DEVICE_LIST) > 1 else basename else: output_name = "recording_{serialno}.mp4".format(serialno=dev.serialno) output = os.path.join(self.args.log, output_name) dev.stop_recording(output) except: traceback.print_exc() def runTest(self): scriptpath, pyfilename = script_dir_name(self.args.script) pyfilepath = os.path.join(scriptpath, pyfilename) pyfilepath = os.path.abspath(pyfilepath) self.scope["__file__"] = pyfilepath with open(pyfilepath, 'r', encoding="utf8") as f: code = f.read() pyfilepath = pyfilepath.encode(sys.getfilesystemencoding()) try: exec(compile(code.encode("utf-8"), pyfilepath, 'exec'), self.scope) except Exception as err: log(err, desc="Final Error", snapshot=True if G.DEVICE_LIST else False) six.reraise(*sys.exc_info()) @classmethod def exec_other_script(cls, scriptpath): """run other script in test script""" warnings.simplefilter("always") warnings.warn("please use using() api instead.", PendingDeprecationWarning) def _sub_dir_name(scriptname): dirname = os.path.splitdrive(os.path.normpath(scriptname))[-1] dirname = dirname.strip(os.path.sep).replace(os.path.sep, "_").replace(cls.SCRIPTEXT, "_sub") return dirname def _copy_script(src, dst): if os.path.isdir(dst): shutil.rmtree(dst, ignore_errors=True) os.mkdir(dst) for f in os.listdir(src): srcfile = os.path.join(src, f) if not (os.path.isfile(srcfile) and f.endswith(cls.TPLEXT)): continue dstfile = os.path.join(dst, f) shutil.copy(srcfile, dstfile) # find script in PROJECT_ROOT scriptpath = os.path.join(ST.PROJECT_ROOT, scriptpath) # copy submodule's images into sub_dir sub_dir = _sub_dir_name(scriptpath) sub_dirpath = os.path.join(cls.args.script, sub_dir) _copy_script(scriptpath, sub_dirpath) # read code pyfilename = os.path.basename(scriptpath).replace(cls.SCRIPTEXT, ".py") pyfilepath = os.path.join(scriptpath, pyfilename) pyfilepath = os.path.abspath(pyfilepath) with open(pyfilepath, 'r', encoding='utf8') as f: code = f.read() # replace tpl filepath with filepath in sub_dir code = re.sub("[\'\"](\w+.png)[\'\"]", "\"%s/\g<1>\"" % sub_dir, code) exec(compile(code.encode("utf8"), pyfilepath, 'exec'), cls.scope)
class AirtestCase(unittest.TestCase): @classmethod def setUpClass(cls): pass def setUpClass(cls): pass def tearDown(self): pass def runTest(self): pass @classmethod def exec_other_script(cls, scriptpath): '''run other script in test script''' pass def _sub_dir_name(scriptname): pass def _copy_script(src, dst): pass
10
1
14
1
12
2
3
0.15
1
5
2
1
3
0
5
77
97
13
73
33
63
11
70
28
62
6
2
4
20
3,323
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/android.py
airtest.core.android.android.Android
class Android(Device): """Android Device Class""" def __init__(self, serialno=None, host=None, cap_method=CAP_METHOD.MINICAP, touch_method=TOUCH_METHOD.MINITOUCH, ime_method=IME_METHOD.YOSEMITEIME, ori_method=ORI_METHOD.MINICAP, display_id=None, input_event=None, adb_path=None, name=None): super(Android, self).__init__() self.serialno = serialno or self.get_default_device(adb_path=adb_path) self._uuid = name or self.serialno self._cap_method = cap_method.upper() self._touch_method = touch_method.upper() self.ime_method = ime_method.upper() self.ori_method = ori_method.upper() self.display_id = display_id self.input_event = input_event # init adb self.adb = ADB(self.serialno, adb_path=adb_path, server_addr=host, display_id=self.display_id, input_event=self.input_event) self.adb.wait_for_device() self.sdk_version = self.adb.sdk_version if self.sdk_version >= SDK_VERISON_ANDROID10 and self._touch_method == TOUCH_METHOD.MINITOUCH: self._touch_method = TOUCH_METHOD.MAXTOUCH self._display_info = {} self._current_orientation = None # init components self.rotation_watcher = RotationWatcher(self.adb, self.ori_method) self.yosemite_ime = YosemiteIme(self.adb) self.yosemite_recorder = Recorder(self.adb) self.yosemite_ext = YosemiteExt(self.adb) self._register_rotation_watcher() self._touch_proxy = None self._screen_proxy = None # recorder self.recorder = None self.recorder_save_path = None @property def touch_proxy(self): """ Perform touch operation according to self.touch_method Module: :py:mod:`airtest.core.android.touch_methods.touch_proxy.TouchProxy` Returns: TouchProxy Examples: >>> dev = Android() >>> dev.touch_proxy.touch((100, 100)) # If the device uses minitouch, it is the same as dev.minitouch.touch >>> dev.touch_proxy.swipe_along([(0,0), (100, 100)]) """ if self._touch_proxy: return self._touch_proxy self._touch_proxy = TouchProxy.auto_setup(self.adb, default_method=self._touch_method, ori_transformer=self._touch_point_by_orientation, size_info=self.display_info, input_event=self.input_event) return self._touch_proxy @touch_proxy.setter def touch_proxy(self, touch_method): """ Specify a touch method, if the method fails to initialize, try to use other methods instead 指定一个触摸方案,如果该方法初始化失败,则尝试使用其他方法代替 Args: touch_method: "MINITOUCH" or Minitouch() object Returns: TouchProxy object Raises: TouchMethodNotSupportedError when the connection fails Examples: >>> dev = Android() >>> dev.touch_proxy = "MINITOUCH" >>> from airtest.core.android.touch_methods.minitouch import Minitouch >>> minitouch = Minitouch(dev.adb) >>> dev.touch_proxy = minitouch """ if self._screen_proxy: self._screen_proxy.teardown() self._touch_proxy = TouchProxy.auto_setup(self.adb, default_method=touch_method, ori_transformer=self._touch_point_by_orientation, size_info=self.display_info, input_event=self.input_event) @property def touch_method(self): """ In order to be compatible with the previous `dev.touch_method` 为了兼容以前的`dev.touch_method` Returns: "MINITOUCH" or "MAXTOUCH" Examples: >>> dev = Android() >>> print(dev.touch_method) # "MINITOUCH" """ return self.touch_proxy.method_name @touch_method.setter def touch_method(self, name): """ Specify the touch method for the device, but this is not recommended 为设备指定触摸方案,但不建议这样做 Just to be compatible with some old codes 仅为了兼容一些旧的代码 Args: name: "MINITOUCH" or Minitouch() object Returns: None Examples: >>> dev = Android() >>> dev.touch_method = "MINITOUCH" """ warnings.warn("No need to manually specify touch_method, airtest will automatically specify a suitable touch method, when airtest>=1.1.2") self.touch_proxy = name @property def cap_method(self): """ In order to be compatible with the previous `dev.cap_method` 为了兼容以前的`dev.cap_method` Returns: "MINICAP" or "JAVACAP" Examples: >>> dev = Android() >>> print(dev.cap_method) # "MINICAP" """ return self.screen_proxy.method_name @cap_method.setter def cap_method(self, name): """ Specify the screen capture method for the device, but this is not recommended 为设备指定屏幕截图方案,但不建议这样做 Just to be compatible with some old codes 仅为了兼容一些旧的代码 Args: name: "MINICAP" or Minicap() object Returns: None Examples: >>> dev = Android() >>> dev.cap_method = "MINICAP" """ warnings.warn("No need to manually specify cap_method, airtest will automatically specify a suitable screenshot method, when airtest>=1.1.2") self.screen_proxy = name @property def screen_proxy(self): """ Similar to touch_proxy, it returns a proxy that can automatically initialize an available screenshot method, such as Minicap Afterwards, you only need to call ``self.screen_proxy.get_frame()`` to get the screenshot 类似touch_proxy,返回一个代理,能够自动初始化一个可用的屏幕截图方法,例如Minicap 后续只需要调用 ``self.screen_proxy.get_frame()``即可获取到屏幕截图 Returns: ScreenProxy(Minicap()) Examples: >>> dev = Android() >>> img = dev.screen_proxy.get_frame_from_stream() # dev.minicap.get_frame_from_stream() is deprecated """ if self._screen_proxy: return self._screen_proxy self._screen_proxy = ScreenProxy.auto_setup(self.adb, default_method=self._cap_method, rotation_watcher=self.rotation_watcher, display_id=self.display_id, ori_function=lambda: self.display_info) return self._screen_proxy @screen_proxy.setter def screen_proxy(self, cap_method): """ Specify a screenshot method, if the method fails to initialize, try to use other methods instead 指定一个截图方法,如果该方法初始化失败,则尝试使用其他方法代替 Args: cap_method: "MINICAP" or :py:mod:`airtest.core.android.cap_methods.minicap.Minicap` object Returns: ScreenProxy object Raises: ScreenError when the connection fails Examples: >>> dev = Android() >>> dev.screen_proxy = "MINICAP" >>> from airtest.core.android.cap_methods.minicap import Minicap >>> minicap = Minicap(dev.adb, rotation_watcher=dev.rotation_watcher) >>> dev.screen_proxy = minicap """ if self._screen_proxy: self._screen_proxy.teardown_stream() self._screen_proxy = ScreenProxy.auto_setup(self.adb, default_method=cap_method) def get_deprecated_var(self, old_name, new_name): """ Get deprecated class variables When the airtest version number>=1.1.2, the call device.minicap/device.javacap is removed, and relevant compatibility is made here, and DeprecationWarning is printed airtest版本号>=1.1.2时,去掉了device.minicap/device.javacap这样的调用,在此做了相关的兼容,并打印DeprecationWarning Usage: Android.minicap=property(lambda self: self.get_deprecated_var("minicap", "screen_proxy")) Args: old_name: "minicap" new_name: "screen_proxy" Returns: New implementation of deprecated object, e.g self.minicap -> self.screen_proxy dev.minicap.get_frame_from_stream() -> dev.screen_proxy.get_frame_from_stream() Examples: >>> dev = Android() >>> isinstance(dev.minicap, ScreenProxy) # True >>> dev.minicap.get_frame_from_stream() # --> dev.screen_proxy.get_frame_from_stream() """ warnings.simplefilter("always") warnings.warn("{old_name} is deprecated, use {new_name} instead".format(old_name=old_name, new_name=new_name), DeprecationWarning) return getattr(self, new_name) def get_default_device(self, adb_path=None): """ Get local default device when no serialno Returns: local device serialno """ if not ADB(adb_path=adb_path).devices(state="device"): raise IndexError("ADB devices not found") return ADB(adb_path=adb_path).devices(state="device")[0][0] @property def uuid(self): """ Serial number :return: """ ult = [self._uuid] if self.display_id: ult.append(self.display_id) if self.input_event: ult.append(self.input_event) return "_".join(ult) def list_app(self, third_only=False): """ Return list of packages Args: third_only: if True, only third party applications are listed Returns: array of applications """ return self.adb.list_app(third_only) def path_app(self, package): """ Print the full path to the package Args: package: package name Returns: the full path to the package """ assert package, "package name should not be empty" return self.adb.path_app(package) def check_app(self, package): """ Check if package exists on the device Args: package: package name Returns: True if package exists on the device Raises: AirtestError: raised if package is not found """ assert package, "package name should not be empty" return self.adb.check_app(package) def start_app(self, package, activity=None): """ Start the application and activity Args: package: package name activity: activity name Returns: None """ assert package, "package name should not be empty" return self.adb.start_app(package, activity) def start_app_timing(self, package, activity): """ Start the application and activity, and measure time Args: package: package name activity: activity name Returns: app launch time """ assert package, "package name should not be empty" return self.adb.start_app_timing(package, activity) def stop_app(self, package): """ Stop the application Args: package: package name Returns: None """ assert package, "package name should not be empty" return self.adb.stop_app(package) def clear_app(self, package): """ Clear all application data Args: package: package name Returns: None """ assert package, "package name should not be empty" return self.adb.clear_app(package) def install_app(self, filepath, replace=False, install_options=None): """ Install the application on the device Args: filepath: full path to the `apk` file to be installed on the device replace: True or False to replace the existing application install_options: list of options, default is [] Returns: output from installation process """ return self.adb.install_app(filepath, replace=replace, install_options=install_options) def install_multiple_app(self, filepath, replace=False, install_options=None): """ Install multiple the application on the device Args: filepath: full path to the `apk` file to be installed on the device replace: True or False to replace the existing application install_options: list of options, default is [] Returns: output from installation process """ return self.adb.install_multiple_app(filepath, replace=replace, install_options=install_options) def uninstall_app(self, package): """ Uninstall the application from the device Args: package: package name Returns: output from the uninstallation process """ assert package, "package name should not be empty" return self.adb.uninstall_app(package) def snapshot(self, filename=None, ensure_orientation=True, quality=10, max_size=None): """ Take the screenshot of the display. The output is send to stdout by default. Args: filename: name of the file where to store the screenshot, default is None which is stdout ensure_orientation: True or False whether to keep the orientation same as display quality: The image quality, integer in range [1, 99] max_size: the maximum size of the picture, e.g 1200 Returns: screenshot output """ # default not write into file. screen = self.screen_proxy.snapshot(ensure_orientation=ensure_orientation) if filename: aircv.imwrite(filename, screen, quality, max_size=max_size) return screen def shell(self, *args, **kwargs): """ Return `adb shell` interpreter Args: *args: optional shell commands **kwargs: optional shell commands Returns: None """ return self.adb.shell(*args, **kwargs) def keyevent(self, keyname, **kwargs): """ Perform keyevent on the device Args: keyname: keyevent name **kwargs: optional arguments Returns: None """ self.adb.keyevent(keyname) def wake(self): """ Perform wake up event Returns: None """ # 先尝试连续发送224和82解锁屏幕,如果解锁失败,再试用yosemite解锁 self.adb.keyevent("KEYCODE_WAKEUP") if self.adb.is_locked(): self.adb.keyevent("KEYCODE_MENU") time.sleep(0.5) if self.adb.is_locked(): self.home() self.yosemite_recorder.install_or_upgrade() # 暂时Yosemite只用了ime self.adb.shell(['am', 'start', '-a', 'com.netease.nie.yosemite.ACTION_IDENTIFY']) time.sleep(0.5) self.home() def home(self): """ Press HOME button Returns: None """ self.keyevent("HOME") def text(self, text, enter=True, **kwargs): """ Input text on the device Args: text: text to input, will automatically replace single quotes with double quotes enter: True or False whether to press `Enter` key search: True or False whether to press `Search` key on IME after input Returns: None """ search = False if "search" not in kwargs else kwargs["search"] if self.ime_method == IME_METHOD.YOSEMITEIME: try: self.yosemite_ime.text(text) except AdbError: # 部分手机如oppo/vivo等,在没有安装/启用yosemite输入法时无法使用,改用adb shell input text输入 self.adb.text(text) else: self.adb.text(text) if search: try: self.yosemite_ime.code("3") except AdbError: self.adb.shell(["input", "keyevent", "84"]) # 游戏输入时,输入有效内容后点击Enter确认,如不需要,enter置为False即可。 if enter: self.adb.shell(["input", "keyevent", "ENTER"]) def touch(self, pos, duration=0.01): """ Perform touch event on the device Args: pos: coordinates (x, y) duration: how long to touch the screen Examples: >>> dev = Android() # or dev = device() >>> dev.touch((100, 100)) # absolute coordinates >>> dev.touch((0.5, 0.5)) # relative coordinates Returns: (x, y) # The coordinate position of the actual click """ pos = get_absolute_coordinate(pos, self) self.touch_proxy.touch(pos, duration) return pos def double_click(self, pos): pos = get_absolute_coordinate(pos, self) self.touch(pos) time.sleep(0.05) self.touch(pos) return pos def swipe(self, p1, p2, duration=0.5, steps=5, fingers=1): """ Perform swipe event on the device Args: p1: start point p2: end point duration: how long to swipe the screen, default 0.5 steps: how big is the swipe step, default 5 fingers: the number of fingers. 1 or 2. Examples: >>> dev = Android() # or dev = device() >>> dev.swipe((100, 100), (200, 200)) # absolute coordinates >>> dev.swipe((0.1, 0.1), (0.2, 0.2)) # relative coordinates Returns: (pos1, pos2) """ p1 = get_absolute_coordinate(p1, self) p2 = get_absolute_coordinate(p2, self) self.touch_proxy.swipe(p1, p2, duration=duration, steps=steps, fingers=fingers) return p1, p2 def pinch(self, center=None, percent=0.5, duration=0.5, steps=5, in_or_out='in'): """ Perform pinch event on the device, only for minitouch and maxtouch Args: center: the center point of the pinch operation percent: pinch distance to half of screen, default is 0.5 duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 in_or_out: pinch in or pinch out, default is 'in' Returns: None Raises: TypeError: An error occurred when center is not a list/tuple or None """ self.touch_proxy.pinch(center=center, percent=percent, duration=duration, steps=steps, in_or_out=in_or_out) def swipe_along(self, coordinates_list, duration=0.8, steps=5): """ Perform swipe event across multiple points in sequence, only for minitouch and maxtouch Args: coordinates_list: list of coordinates: [(x1, y1), (x2, y2), (x3, y3)] duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 Returns: None """ coordinates_list = [get_absolute_coordinate(pos, self) for pos in coordinates_list] self.touch_proxy.swipe_along(coordinates_list, duration=duration, steps=steps) def two_finger_swipe(self, tuple_from_xy, tuple_to_xy, duration=0.8, steps=5, offset=(0, 50)): """ Perform two finger swipe action, only for minitouch and maxtouch Args: tuple_from_xy: start point tuple_to_xy: end point duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 offset: coordinate offset of the second finger, default is (0, 50) Returns: None """ tuple_from_xy = get_absolute_coordinate(tuple_from_xy, self) tuple_to_xy = get_absolute_coordinate(tuple_to_xy, self) self.touch_proxy.two_finger_swipe(tuple_from_xy, tuple_to_xy, duration=duration, steps=steps, offset=offset) def logcat(self, *args, **kwargs): """ Perform `logcat`operations Args: *args: optional arguments **kwargs: optional arguments Returns: `logcat` output """ return self.adb.logcat(*args, **kwargs) def getprop(self, key, strip=True): """ Get properties for given key Args: key: key name strip: True or False whether to strip the output or not Returns: property value(s) """ return self.adb.getprop(key, strip) def get_ip_address(self): """ Perform several set of commands to obtain the IP address * `adb shell netcfg | grep wlan0` * `adb shell ifconfig` * `adb getprop dhcp.wlan0.ipaddress` Returns: None if no IP address has been found, otherwise return the IP address """ return self.adb.get_ip_address() def get_top_activity(self): """ Get the top activity Returns: (package, activity, pid) """ return self.adb.get_top_activity() def get_top_activity_name(self): """ Get the top activity name Returns: package/activity """ tanp = self.get_top_activity() if tanp: return tanp[0] + '/' + tanp[1] else: return None def is_keyboard_shown(self): """ Return True or False whether soft keyboard is shown or not Notes: Might not work on all devices Returns: True or False """ return self.adb.is_keyboard_shown() def is_screenon(self): """ Return True or False whether the screen is on or not Notes: Might not work on all devices Returns: True or False """ return self.adb.is_screenon() def is_locked(self): """ Return True or False whether the device is locked or not Notes: Might not work on some devices Returns: True or False """ return self.adb.is_locked() def unlock(self): """ Unlock the device Notes: Might not work on all devices Returns: None """ return self.adb.unlock() @property def display_info(self): """ Return the display info (width, height, orientation and max_x, max_y) Returns: display information """ if not self._display_info: self._display_info = self.get_display_info() display_info = copy(self._display_info) # update ow orientation, which is more accurate if self._current_orientation is not None: display_info.update({ "rotation": self._current_orientation * 90, "orientation": self._current_orientation, }) return display_info def get_display_info(self): """ Return the display info (width, height, orientation and max_x, max_y) Returns: display information """ self.rotation_watcher.get_ready() return self.adb.get_display_info() def get_current_resolution(self): """ Return current resolution after rotation Returns: width and height of the display """ # 注意黑边问题,需要用安卓接口获取区分两种分辨率 w, h = self.display_info["width"], self.display_info["height"] if self.display_info["orientation"] in [1, 3]: w, h = h, w return w, h def get_render_resolution(self, refresh=False, package=None): """ Return render resolution after rotation Args: refresh: whether to force refresh render resolution package: package name, default to the package of top activity Returns: offset_x, offset_y, offset_width and offset_height of the display """ if refresh or 'offset_x' not in self._display_info: self.adjust_all_screen(package) x, y, w, h = self._display_info.get('offset_x', 0), \ self._display_info.get('offset_y', 0), \ self._display_info.get('offset_width', 0), \ self._display_info.get('offset_height', 0) if self.display_info["orientation"] in [1, 3]: x, y, w, h = y, x, h, w return x, y, w, h def start_recording(self, max_time=1800, output=None, fps=10, mode="yosemite", snapshot_sleep=0.001, orientation=0, bit_rate_level=None, bit_rate=None, max_size=None, *args, **kwargs): """ Start recording the device display Args: max_time: maximum screen recording time, default is 1800 output: ouput file path mode: the backend write video, choose in ["ffmpeg", "yosemite"] yosemite: (default method) High clarity but large file size and limited phone compatibility. ffmpeg: Lower image quality but smaller files and better compatibility. fps: frames per second will record snapshot_sleep: (mode="ffmpeg" only) sleep time for each snapshot. orientation: 1: portrait, 2: landscape, 0: rotation, default is 0 bit_rate_level: (mode="yosemite" only) bit_rate=resolution*level, 0 < level <= 5, default is 1 bit_rate: (mode="yosemite" only) the higher the bitrate, the clearer the video max_size: (mode="ffmpeg" only) max size of the video frame, e.g.800, default is None. Smaller sizes lead to lower system load. Returns: save_path: path of video file Examples: Record 30 seconds of video and export to the current directory test.mp4: >>> from airtest.core.api import connect_device, sleep >>> dev = connect_device("Android:///") >>> save_path = dev.start_recording(output="test.mp4") >>> sleep(30) >>> dev.stop_recording() >>> print(save_path) >>> # the screen is portrait >>> portrait_mp4 = dev.start_recording(output="portrait.mp4", orientation=1) # or orientation="portrait" >>> sleep(30) >>> dev.stop_recording() >>> # the screen is landscape >>> landscape_mp4 = dev.start_recording(output="landscape.mp4", orientation=2) # or orientation="landscape" In ffmpeg mode, you can specify max_size to limit the video's maximum width/length. Smaller video sizes result in lower CPU load. >>> dev.start_recording(output="test.mp4", mode="ffmpeg", max_size=800) """ logdir = "./" if ST.LOG_DIR is not None: logdir = ST.LOG_DIR if output is None: save_path = os.path.join(logdir, "screen_%s.mp4" % (time.strftime("%Y%m%d%H%M%S", time.localtime()))) else: save_path = output if os.path.isabs(output) else os.path.join(logdir, output) self.recorder_save_path = save_path if mode == "yosemite": if self.yosemite_recorder.recording_proc != None: LOGGING.warning( "recording is already running, please don't call again") return None if not bit_rate: if not bit_rate_level: bit_rate_level = 1 if bit_rate_level > 5: bit_rate_level = 5 bit_rate = self.display_info['width'] * \ self.display_info['height'] * bit_rate_level if orientation == 1: bool_is_vertical = "true" elif orientation == 2: bool_is_vertical = "false" else: bool_is_vertical = "off" self.yosemite_recorder.start_recording( max_time=max_time, bit_rate=bit_rate, bool_is_vertical=bool_is_vertical) return save_path if fps > 10 or fps < 1: LOGGING.warning("fps should be between 1 and 10, becuase of the recording effiency") if fps > 10: fps = 10 if fps < 1: fps = 1 if self.recorder and self.recorder.is_running(): LOGGING.warning("recording is already running, please don't call again") return None max_size = get_max_size(max_size) def get_frame(): data = self.screen_proxy.get_frame_from_stream() frame = aircv.utils.string_2_img(data) if max_size is not None: frame = resize_by_max(frame, max_size) return frame self.recorder = ScreenRecorder( save_path, get_frame, fps=fps, snapshot_sleep=snapshot_sleep, orientation=orientation) self.recorder.stop_time = max_time self.recorder.start() LOGGING.info("start recording screen to {}".format(save_path)) return save_path def stop_recording(self, output=None, is_interrupted=None): """ Stop recording the device display. Recoding file will be kept in the device. """ if self.yosemite_recorder.recording_proc is not None or self.recorder is None: if output is None: output = self.recorder_save_path return self.yosemite_recorder.stop_recording(output=output, is_interrupted=is_interrupted) LOGGING.info("stopping recording") self.recorder.stop() self.recorder = None if output and not is_interrupted: shutil.move(self.recorder_save_path, output) LOGGING.info("save video to {}".format(output)) return True def get_clipboard(self): """ Get the clipboard content Returns: clipboard content Examples: >>> dev = Android() >>> dev.set_clipboard("hello world") >>> dev.get_clipboard() 'hello world' >>> dev.paste() # paste the clipboard content """ return self.yosemite_ext.get_clipboard() def set_clipboard(self, text): """ Set the clipboard content Args: text: text to set Returns: None """ self.yosemite_ext.set_clipboard(text) def push(self, local, remote): """ Push file to the device Args: local: local file or folder to be copied to the device remote: destination on the device where the file will be copied Returns: The file path saved in the phone may be enclosed in quotation marks, eg. '"test\ file.txt"' Examples: >>> dev = connect_device("android:///") >>> dev.push("test.txt", "/sdcard/test.txt") """ return self.adb.push(local, remote) def pull(self, remote, local=""): """ Pull file from the device Args: remote: remote file to be downloaded from the device local: local destination where the file will be downloaded from the device, if not specified, the current directory is used Returns: None Examples: >>> dev = connect_device("android:///") >>> dev.pull("/sdcard/test.txt", "rename.txt") """ return self.adb.pull(remote, local=local) def _register_rotation_watcher(self): """ Register callbacks for Android and minicap when rotation of screen has changed callback is called in another thread, so be careful about thread-safety Returns: None """ self.rotation_watcher.reg_callback(lambda x: setattr(self, "_current_orientation", x)) def _touch_point_by_orientation(self, tuple_xy): """ Convert image coordinates to physical display coordinates, the arbitrary point (origin) is upper left corner of the device physical display Args: tuple_xy: image coordinates (x, y) Returns: """ x, y = tuple_xy x, y = XYTransformer.up_2_ori( (x, y), (self.display_info["width"], self.display_info["height"]), self.display_info["orientation"] ) return x, y def adjust_all_screen(self, package=None): """ Adjust the render resolution for all_screen device. Args: package: package name, default to the package of top activity Return: None """ info = self.display_info ret = self.adb.get_display_of_all_screen(info, package) if ret: info.update(ret) self._display_info = info def disconnect(self): """ Disconnect the device 1. stop minicap/javacap 2. stop minitouch/maxtouch 3. stop rotation_watcher Returns: None """ self.screen_proxy.teardown_stream() self.touch_proxy.teardown() self.rotation_watcher.teardown()
class Android(Device): '''Android Device Class''' def __init__(self, serialno=None, host=None, cap_method=CAP_METHOD.MINICAP, touch_method=TOUCH_METHOD.MINITOUCH, ime_method=IME_METHOD.YOSEMITEIME, ori_method=ORI_METHOD.MINICAP, display_id=None, input_event=None, adb_path=None, name=None): pass @property def touch_proxy(self): ''' Perform touch operation according to self.touch_method Module: :py:mod:`airtest.core.android.touch_methods.touch_proxy.TouchProxy` Returns: TouchProxy Examples: >>> dev = Android() >>> dev.touch_proxy.touch((100, 100)) # If the device uses minitouch, it is the same as dev.minitouch.touch >>> dev.touch_proxy.swipe_along([(0,0), (100, 100)]) ''' pass @touch_proxy.setter def touch_proxy(self): ''' Specify a touch method, if the method fails to initialize, try to use other methods instead 指定一个触摸方案,如果该方法初始化失败,则尝试使用其他方法代替 Args: touch_method: "MINITOUCH" or Minitouch() object Returns: TouchProxy object Raises: TouchMethodNotSupportedError when the connection fails Examples: >>> dev = Android() >>> dev.touch_proxy = "MINITOUCH" >>> from airtest.core.android.touch_methods.minitouch import Minitouch >>> minitouch = Minitouch(dev.adb) >>> dev.touch_proxy = minitouch ''' pass @property def touch_method(self): ''' In order to be compatible with the previous `dev.touch_method` 为了兼容以前的`dev.touch_method` Returns: "MINITOUCH" or "MAXTOUCH" Examples: >>> dev = Android() >>> print(dev.touch_method) # "MINITOUCH" ''' pass @touch_method.setter def touch_method(self): ''' Specify the touch method for the device, but this is not recommended 为设备指定触摸方案,但不建议这样做 Just to be compatible with some old codes 仅为了兼容一些旧的代码 Args: name: "MINITOUCH" or Minitouch() object Returns: None Examples: >>> dev = Android() >>> dev.touch_method = "MINITOUCH" ''' pass @property def cap_method(self): ''' In order to be compatible with the previous `dev.cap_method` 为了兼容以前的`dev.cap_method` Returns: "MINICAP" or "JAVACAP" Examples: >>> dev = Android() >>> print(dev.cap_method) # "MINICAP" ''' pass @cap_method.setter def cap_method(self): ''' Specify the screen capture method for the device, but this is not recommended 为设备指定屏幕截图方案,但不建议这样做 Just to be compatible with some old codes 仅为了兼容一些旧的代码 Args: name: "MINICAP" or Minicap() object Returns: None Examples: >>> dev = Android() >>> dev.cap_method = "MINICAP" ''' pass @property def screen_proxy(self): ''' Similar to touch_proxy, it returns a proxy that can automatically initialize an available screenshot method, such as Minicap Afterwards, you only need to call ``self.screen_proxy.get_frame()`` to get the screenshot 类似touch_proxy,返回一个代理,能够自动初始化一个可用的屏幕截图方法,例如Minicap 后续只需要调用 ``self.screen_proxy.get_frame()``即可获取到屏幕截图 Returns: ScreenProxy(Minicap()) Examples: >>> dev = Android() >>> img = dev.screen_proxy.get_frame_from_stream() # dev.minicap.get_frame_from_stream() is deprecated ''' pass @screen_proxy.setter def screen_proxy(self): ''' Specify a screenshot method, if the method fails to initialize, try to use other methods instead 指定一个截图方法,如果该方法初始化失败,则尝试使用其他方法代替 Args: cap_method: "MINICAP" or :py:mod:`airtest.core.android.cap_methods.minicap.Minicap` object Returns: ScreenProxy object Raises: ScreenError when the connection fails Examples: >>> dev = Android() >>> dev.screen_proxy = "MINICAP" >>> from airtest.core.android.cap_methods.minicap import Minicap >>> minicap = Minicap(dev.adb, rotation_watcher=dev.rotation_watcher) >>> dev.screen_proxy = minicap ''' pass def get_deprecated_var(self, old_name, new_name): ''' Get deprecated class variables When the airtest version number>=1.1.2, the call device.minicap/device.javacap is removed, and relevant compatibility is made here, and DeprecationWarning is printed airtest版本号>=1.1.2时,去掉了device.minicap/device.javacap这样的调用,在此做了相关的兼容,并打印DeprecationWarning Usage: Android.minicap=property(lambda self: self.get_deprecated_var("minicap", "screen_proxy")) Args: old_name: "minicap" new_name: "screen_proxy" Returns: New implementation of deprecated object, e.g self.minicap -> self.screen_proxy dev.minicap.get_frame_from_stream() -> dev.screen_proxy.get_frame_from_stream() Examples: >>> dev = Android() >>> isinstance(dev.minicap, ScreenProxy) # True >>> dev.minicap.get_frame_from_stream() # --> dev.screen_proxy.get_frame_from_stream() ''' pass def get_default_device(self, adb_path=None): ''' Get local default device when no serialno Returns: local device serialno ''' pass @property def uuid(self): ''' Serial number :return: ''' pass def list_app(self, third_only=False): ''' Return list of packages Args: third_only: if True, only third party applications are listed Returns: array of applications ''' pass def path_app(self, package): ''' Print the full path to the package Args: package: package name Returns: the full path to the package ''' pass def check_app(self, package): ''' Check if package exists on the device Args: package: package name Returns: True if package exists on the device Raises: AirtestError: raised if package is not found ''' pass def start_app(self, package, activity=None): ''' Start the application and activity Args: package: package name activity: activity name Returns: None ''' pass def start_app_timing(self, package, activity): ''' Start the application and activity, and measure time Args: package: package name activity: activity name Returns: app launch time ''' pass def stop_app(self, package): ''' Stop the application Args: package: package name Returns: None ''' pass def clear_app(self, package): ''' Clear all application data Args: package: package name Returns: None ''' pass def install_app(self, filepath, replace=False, install_options=None): ''' Install the application on the device Args: filepath: full path to the `apk` file to be installed on the device replace: True or False to replace the existing application install_options: list of options, default is [] Returns: output from installation process ''' pass def install_multiple_app(self, filepath, replace=False, install_options=None): ''' Install multiple the application on the device Args: filepath: full path to the `apk` file to be installed on the device replace: True or False to replace the existing application install_options: list of options, default is [] Returns: output from installation process ''' pass def uninstall_app(self, package): ''' Uninstall the application from the device Args: package: package name Returns: output from the uninstallation process ''' pass def snapshot(self, filename=None, ensure_orientation=True, quality=10, max_size=None): ''' Take the screenshot of the display. The output is send to stdout by default. Args: filename: name of the file where to store the screenshot, default is None which is stdout ensure_orientation: True or False whether to keep the orientation same as display quality: The image quality, integer in range [1, 99] max_size: the maximum size of the picture, e.g 1200 Returns: screenshot output ''' pass def shell(self, *args, **kwargs): ''' Return `adb shell` interpreter Args: *args: optional shell commands **kwargs: optional shell commands Returns: None ''' pass def keyevent(self, keyname, **kwargs): ''' Perform keyevent on the device Args: keyname: keyevent name **kwargs: optional arguments Returns: None ''' pass def wake(self): ''' Perform wake up event Returns: None ''' pass def home(self): ''' Press HOME button Returns: None ''' pass def text(self, text, enter=True, **kwargs): ''' Input text on the device Args: text: text to input, will automatically replace single quotes with double quotes enter: True or False whether to press `Enter` key search: True or False whether to press `Search` key on IME after input Returns: None ''' pass def touch_proxy(self): ''' Perform touch event on the device Args: pos: coordinates (x, y) duration: how long to touch the screen Examples: >>> dev = Android() # or dev = device() >>> dev.touch((100, 100)) # absolute coordinates >>> dev.touch((0.5, 0.5)) # relative coordinates Returns: (x, y) # The coordinate position of the actual click ''' pass def double_click(self, pos): pass def swipe(self, p1, p2, duration=0.5, steps=5, fingers=1): ''' Perform swipe event on the device Args: p1: start point p2: end point duration: how long to swipe the screen, default 0.5 steps: how big is the swipe step, default 5 fingers: the number of fingers. 1 or 2. Examples: >>> dev = Android() # or dev = device() >>> dev.swipe((100, 100), (200, 200)) # absolute coordinates >>> dev.swipe((0.1, 0.1), (0.2, 0.2)) # relative coordinates Returns: (pos1, pos2) ''' pass def pinch(self, center=None, percent=0.5, duration=0.5, steps=5, in_or_out='in'): ''' Perform pinch event on the device, only for minitouch and maxtouch Args: center: the center point of the pinch operation percent: pinch distance to half of screen, default is 0.5 duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 in_or_out: pinch in or pinch out, default is 'in' Returns: None Raises: TypeError: An error occurred when center is not a list/tuple or None ''' pass def swipe_along(self, coordinates_list, duration=0.8, steps=5): ''' Perform swipe event across multiple points in sequence, only for minitouch and maxtouch Args: coordinates_list: list of coordinates: [(x1, y1), (x2, y2), (x3, y3)] duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 Returns: None ''' pass def two_finger_swipe(self, tuple_from_xy, tuple_to_xy, duration=0.8, steps=5, offset=(0, 50)): ''' Perform two finger swipe action, only for minitouch and maxtouch Args: tuple_from_xy: start point tuple_to_xy: end point duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 offset: coordinate offset of the second finger, default is (0, 50) Returns: None ''' pass def logcat(self, *args, **kwargs): ''' Perform `logcat`operations Args: *args: optional arguments **kwargs: optional arguments Returns: `logcat` output ''' pass def getprop(self, key, strip=True): ''' Get properties for given key Args: key: key name strip: True or False whether to strip the output or not Returns: property value(s) ''' pass def get_ip_address(self): ''' Perform several set of commands to obtain the IP address * `adb shell netcfg | grep wlan0` * `adb shell ifconfig` * `adb getprop dhcp.wlan0.ipaddress` Returns: None if no IP address has been found, otherwise return the IP address ''' pass def get_top_activity(self): ''' Get the top activity Returns: (package, activity, pid) ''' pass def get_top_activity_name(self): ''' Get the top activity name Returns: package/activity ''' pass def is_keyboard_shown(self): ''' Return True or False whether soft keyboard is shown or not Notes: Might not work on all devices Returns: True or False ''' pass def is_screenon(self): ''' Return True or False whether the screen is on or not Notes: Might not work on all devices Returns: True or False ''' pass def is_locked(self): ''' Return True or False whether the device is locked or not Notes: Might not work on some devices Returns: True or False ''' pass def unlock(self): ''' Unlock the device Notes: Might not work on all devices Returns: None ''' pass @property def display_info(self): ''' Return the display info (width, height, orientation and max_x, max_y) Returns: display information ''' pass def get_display_info(self): ''' Return the display info (width, height, orientation and max_x, max_y) Returns: display information ''' pass def get_current_resolution(self): ''' Return current resolution after rotation Returns: width and height of the display ''' pass def get_render_resolution(self, refresh=False, package=None): ''' Return render resolution after rotation Args: refresh: whether to force refresh render resolution package: package name, default to the package of top activity Returns: offset_x, offset_y, offset_width and offset_height of the display ''' pass def start_recording(self, max_time=1800, output=None, fps=10, mode="yosemite", snapshot_sleep=0.001, orientation=0, bit_rate_level=None, bit_rate=None, max_size=None, *args, **kwargs): ''' Start recording the device display Args: max_time: maximum screen recording time, default is 1800 output: ouput file path mode: the backend write video, choose in ["ffmpeg", "yosemite"] yosemite: (default method) High clarity but large file size and limited phone compatibility. ffmpeg: Lower image quality but smaller files and better compatibility. fps: frames per second will record snapshot_sleep: (mode="ffmpeg" only) sleep time for each snapshot. orientation: 1: portrait, 2: landscape, 0: rotation, default is 0 bit_rate_level: (mode="yosemite" only) bit_rate=resolution*level, 0 < level <= 5, default is 1 bit_rate: (mode="yosemite" only) the higher the bitrate, the clearer the video max_size: (mode="ffmpeg" only) max size of the video frame, e.g.800, default is None. Smaller sizes lead to lower system load. Returns: save_path: path of video file Examples: Record 30 seconds of video and export to the current directory test.mp4: >>> from airtest.core.api import connect_device, sleep >>> dev = connect_device("Android:///") >>> save_path = dev.start_recording(output="test.mp4") >>> sleep(30) >>> dev.stop_recording() >>> print(save_path) >>> # the screen is portrait >>> portrait_mp4 = dev.start_recording(output="portrait.mp4", orientation=1) # or orientation="portrait" >>> sleep(30) >>> dev.stop_recording() >>> # the screen is landscape >>> landscape_mp4 = dev.start_recording(output="landscape.mp4", orientation=2) # or orientation="landscape" In ffmpeg mode, you can specify max_size to limit the video's maximum width/length. Smaller video sizes result in lower CPU load. >>> dev.start_recording(output="test.mp4", mode="ffmpeg", max_size=800) ''' pass def get_frame(): pass def stop_recording(self, output=None, is_interrupted=None): ''' Stop recording the device display. Recoding file will be kept in the device. ''' pass def get_clipboard(self): ''' Get the clipboard content Returns: clipboard content Examples: >>> dev = Android() >>> dev.set_clipboard("hello world") >>> dev.get_clipboard() 'hello world' >>> dev.paste() # paste the clipboard content ''' pass def set_clipboard(self, text): ''' Set the clipboard content Args: text: text to set Returns: None ''' pass def push(self, local, remote): ''' Push file to the device Args: local: local file or folder to be copied to the device remote: destination on the device where the file will be copied Returns: The file path saved in the phone may be enclosed in quotation marks, eg. '"test\ file.txt"' Examples: >>> dev = connect_device("android:///") >>> dev.push("test.txt", "/sdcard/test.txt") ''' pass def pull(self, remote, local=""): ''' Pull file from the device Args: remote: remote file to be downloaded from the device local: local destination where the file will be downloaded from the device, if not specified, the current directory is used Returns: None Examples: >>> dev = connect_device("android:///") >>> dev.pull("/sdcard/test.txt", "rename.txt") ''' pass def _register_rotation_watcher(self): ''' Register callbacks for Android and minicap when rotation of screen has changed callback is called in another thread, so be careful about thread-safety Returns: None ''' pass def _touch_point_by_orientation(self, tuple_xy): ''' Convert image coordinates to physical display coordinates, the arbitrary point (origin) is upper left corner of the device physical display Args: tuple_xy: image coordinates (x, y) Returns: ''' pass def adjust_all_screen(self, package=None): ''' Adjust the render resolution for all_screen device. Args: package: package name, default to the package of top activity Return: None ''' pass def disconnect(self): ''' Disconnect the device 1. stop minicap/javacap 2. stop minitouch/maxtouch 3. stop rotation_watcher Returns: None ''' pass
69
56
18
3
6
9
2
1.51
1
18
15
0
57
20
57
81
1,095
257
334
114
255
505
282
94
223
15
2
3
100
3,324
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/cap_methods/adbcap.py
airtest.core.android.cap_methods.adbcap.AdbCap
class AdbCap(BaseCap): def get_frame_from_stream(self): warnings.warn("Currently using ADB screenshots, the efficiency may be very low.") return self.adb.snapshot() def snapshot(self, ensure_orientation=True): screen = super(AdbCap, self).snapshot() if ensure_orientation and self.adb.sdk_version <= SDK_VERISON_ANDROID7: screen = aircv.rotate(screen, self.adb.display_info["orientation"] * 90, clockwise=False) return screen
class AdbCap(BaseCap): def get_frame_from_stream(self): pass def snapshot(self, ensure_orientation=True): pass
3
0
4
0
4
0
2
0
1
1
0
0
2
0
2
7
10
1
9
4
6
0
9
4
6
2
2
1
3
3,325
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/constant.py
airtest.core.android.constant.CAP_METHOD
class CAP_METHOD(object): MINICAP = "MINICAP" ADBCAP = "ADBCAP" JAVACAP = "JAVACAP"
class CAP_METHOD(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
1
0
0
3,326
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/bytecode.py
airtest.utils.apkparser.bytecode.MethodBC
class MethodBC(object): def show(self, value): getattr(self, "show_" + value)()
class MethodBC(object): def show(self, value): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
3,327
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/bytecode.py
airtest.utils.apkparser.bytecode.BuffHandle
class BuffHandle: def __init__(self, buff): self.__buff = buff self.__idx = 0 def read_b(self, size): return self.__buff[ self.__idx: self.__idx + size ] def read(self, size): if isinstance(size, SV): size = size.value buff = self.__buff[ self.__idx: self.__idx + size ] self.__idx += size return buff def end(self): return self.__idx == len(self.__buff)
class BuffHandle: def __init__(self, buff): pass def read_b(self, size): pass def read_b(self, size): pass def end(self): pass
5
0
4
1
3
0
1
0
0
1
1
0
4
2
4
4
19
5
14
8
9
0
14
8
9
2
0
1
5
3,328
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/bytecode.py
airtest.utils.apkparser.bytecode.Buff
class Buff: def __init__(self, offset, buff): self.offset = offset self.buff = buff self.size = len(buff)
class Buff: def __init__(self, offset, buff): pass
2
0
5
1
4
0
1
0
0
0
0
0
1
3
1
1
6
1
5
5
3
0
5
5
3
1
0
0
1
3,329
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/axmlprinter.py
airtest.utils.apkparser.axmlprinter.AXMLPrinter
class AXMLPrinter: def __init__(self, raw_buff): self.axml = AXMLParser(raw_buff) self.xmlns = False self.buff = "" while 1: _type = self.axml.next() #print "tagtype = ", _type if _type == tc.START_DOCUMENT: self.buff += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" elif _type == tc.START_TAG: self.buff += "<%s%s\n" % (self.getPrefix(self.axml.getPrefix()), self.axml.getName()) # FIXME: use namespace if self.xmlns == False: self.buff += "xmlns:%s=\"%s\"\n" % (self.axml.getNamespacePrefix(0), self.axml.getNamespaceUri(0)) self.xmlns = True for i in range(0, self.axml.getAttributeCount()): self.buff += "%s%s=\"%s\"\n" % (self.getPrefix(self.axml.getAttributePrefix(i)), self.axml.getAttributeName(i), self.getAttributeValue(i)) self.buff += ">\n" elif _type == tc.END_TAG: self.buff += "</%s%s>\n" % (self.getPrefix(self.axml.getPrefix()), self.axml.getName()) elif _type == tc.TEXT: self.buff += "%s\n" % self.axml.getText() elif _type == tc.END_DOCUMENT: break def getBuff(self): return self.buff.encode("utf-8") def getPrefix(self, prefix): if prefix == None or len(prefix) == 0: return "" return prefix + ":" def getAttributeValue(self, index): _type = self.axml.getAttributeValueType(index) _data = self.axml.getAttributeValueData(index) #print _type, _data if _type == tc.TYPE_STRING: return saxutils.escape(self.axml.getAttributeValue(index), entities={'"': '&quot;'}) elif _type == tc.TYPE_ATTRIBUTE: return "?%s%08X" % (self.getPackage(_data), _data) elif _type == tc.TYPE_REFERENCE: return "@%s%08X" % (self.getPackage(_data), _data) # WIP elif _type == tc.TYPE_FLOAT: return "%f" % unpack("=f", pack("=L", _data))[0] elif _type == tc.TYPE_INT_HEX: return "0x%08X" % _data elif _type == tc.TYPE_INT_BOOLEAN: if _data == 0: return "false" return "true" elif _type == tc.TYPE_DIMENSION: return "%f%s" % (self.complexToFloat(_data), tc.DIMENSION_UNITS[_data & tc.COMPLEX_UNIT_MASK]) elif _type == tc.TYPE_FRACTION: return "%f%s" % (self.complexToFloat(_data), tc.FRACTION_UNITS[_data & tc.COMPLEX_UNIT_MASK]) elif _type >= tc.TYPE_FIRST_COLOR_INT and _type <= tc.TYPE_LAST_COLOR_INT: return "#%08X" % _data elif _type >= tc.TYPE_FIRST_INT and _type <= tc.TYPE_LAST_INT: if _data > 0x7fffffff: _data = (0x7fffffff & _data) - 0x80000000 return "%d" % _data elif _type == tc.TYPE_INT_DEC: return "%d" % _data # raise exception here? return "<0x%X, type 0x%02X>" % (_data, _type) def complexToFloat(self, xcomplex): return (float)(xcomplex & 0xFFFFFF00) * tc.RADIX_MULTS[(xcomplex>>4) & 3]; def getPackage(self, id): if id >> 24 == 1: return "android:" return ""
class AXMLPrinter: def __init__(self, raw_buff): pass def getBuff(self): pass def getPrefix(self, prefix): pass def getAttributeValue(self, index): pass def complexToFloat(self, xcomplex): pass def getPackage(self, id): pass
7
0
15
4
11
1
5
0.09
0
3
1
0
6
3
6
6
96
26
65
14
58
6
51
14
44
14
0
3
29
3,330
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/axmlparser.py
airtest.utils.apkparser.axmlparser.AXMLParser
class AXMLParser: def __init__(self, raw_buff): self.reset() self.buff = bytecode.BuffHandle(raw_buff) self.buff.read(4) self.buff.read(4) self.sb = StringBlock(self.buff) self.m_resourceIDs = [] self.m_prefixuri = {} self.m_uriprefix = {} self.m_prefixuriL = [] def reset(self): self.m_event = -1 self.m_lineNumber = -1 self.m_name = -1 self.m_namespaceUri = -1 self.m_attributes = [] self.m_idAttribute = -1 self.m_classAttribute = -1 self.m_styleAttribute = -1 def next(self): self.doNext() return self.m_event def doNext(self): if self.m_event == tc.END_DOCUMENT: return event = self.m_event self.reset() while 1: chunkType = -1 # Fake END_DOCUMENT event. if event == tc.END_TAG: pass # START_DOCUMENT if event == tc.START_DOCUMENT: chunkType = tc.CHUNK_XML_START_TAG else: if self.buff.end() == True: self.m_event = tc.END_DOCUMENT break chunkType = SV('<L', self.buff.read(4)).get_value() if chunkType == tc.CHUNK_RESOURCEIDS: chunkSize = SV('<L', self.buff.read(4)).get_value() # FIXME if chunkSize < 8 or chunkSize%4 != 0: raise("ooo") for i in range(0, int(chunkSize/4-2)): self.m_resourceIDs.append(SV('<L', self.buff.read(4))) continue # FIXME if chunkType < tc.CHUNK_XML_FIRST or chunkType > tc.CHUNK_XML_LAST: raise("ooo") # Fake START_DOCUMENT event. if chunkType == tc.CHUNK_XML_START_TAG and event == -1: self.m_event = tc.START_DOCUMENT break self.buff.read(4) #/*chunkSize*/ lineNumber = SV('<L', self.buff.read(4)).get_value() self.buff.read(4) #0xFFFFFFFF if chunkType == tc.CHUNK_XML_START_NAMESPACE or chunkType == tc.CHUNK_XML_END_NAMESPACE: if chunkType == tc.CHUNK_XML_START_NAMESPACE: prefix = SV('<L', self.buff.read(4)).get_value() uri = SV('<L', self.buff.read(4)).get_value() self.m_prefixuri[ prefix ] = uri self.m_uriprefix[ uri ] = prefix self.m_prefixuriL.append((prefix, uri)) else: self.buff.read(4) self.buff.read(4) (prefix, uri) = self.m_prefixuriL.pop() #del self.m_prefixuri[ prefix ] #del self.m_uriprefix[ uri ] continue self.m_lineNumber = lineNumber if chunkType == tc.CHUNK_XML_START_TAG: self.m_namespaceUri = SV('<L', self.buff.read(4)).get_value() self.m_name = SV('<L', self.buff.read(4)).get_value() # FIXME self.buff.read(4) #flags attributeCount = SV('<L', self.buff.read(4)).get_value() self.m_idAttribute = (attributeCount>>16) - 1 attributeCount = attributeCount & 0xFFFF self.m_classAttribute = SV('<L', self.buff.read(4)).get_value() self.m_styleAttribute = (self.m_classAttribute>>16) - 1 self.m_classAttribute = (self.m_classAttribute & 0xFFFF) - 1 for i in range(0, attributeCount * tc.ATTRIBUTE_LENGTH): self.m_attributes.append(SV('<L', self.buff.read(4)).get_value()) for i in range(tc.ATTRIBUTE_IX_VALUE_TYPE, len(self.m_attributes), tc.ATTRIBUTE_LENGTH): self.m_attributes[i] = (self.m_attributes[i]>>24) self.m_event = tc.START_TAG break if chunkType == tc.CHUNK_XML_END_TAG: self.m_namespaceUri = SV('<L', self.buff.read(4)).get_value() self.m_name = SV('<L', self.buff.read(4)).get_value() self.m_event = tc.END_TAG break if chunkType == tc.CHUNK_XML_TEXT: self.m_name = SV('<L', self.buff.read(4)).get_value() # FIXME self.buff.read(4) #? self.buff.read(4) #? self.m_event = tc.TEXT break def getPrefixByUri(self, uri): try: return self.m_uriprefix[ uri ] except KeyError: return -1 def getPrefix(self): try: return self.sb.getRaw(self.m_prefixuri[ self.m_namespaceUri ]) except KeyError: return "" def getName(self): if self.m_name == -1 or (self.m_event != tc.START_TAG and self.m_event != tc.END_TAG): return "" return self.sb.getRaw(self.m_name) def getText(self): if self.m_name == -1 or self.m_event != tc.TEXT: return "" return self.sb.getRaw(self.m_name) def getNamespacePrefix(self, pos): prefix = self.m_prefixuriL[ pos ][0] return self.sb.getRaw(prefix) def getNamespaceUri(self, pos): uri = self.m_prefixuriL[ pos ][1] return self.sb.getRaw(uri) def getNamespaceCount(self, pos): pass def getAttributeOffset(self, index): # FIXME if self.m_event != tc.START_TAG: raise("Current event is not START_TAG.") offset = index * 5 # FIXME if offset >= len(self.m_attributes): raise("Invalid attribute index") return offset def getAttributeCount(self): if self.m_event != tc.START_TAG: return -1 return int(len(self.m_attributes) / tc.ATTRIBUTE_LENGTH) def getAttributePrefix(self, index): offset = self.getAttributeOffset(index) uri = self.m_attributes[offset + tc.ATTRIBUTE_IX_NAMESPACE_URI] prefix = self.getPrefixByUri(uri) if prefix == -1: return "" return self.sb.getRaw(prefix) def getAttributeName(self, index): offset = self.getAttributeOffset(index) name = self.m_attributes[offset + tc.ATTRIBUTE_IX_NAME] if name == -1: return "" return self.sb.getRaw(name) def getAttributeValueType(self, index): offset = self.getAttributeOffset(index) return self.m_attributes[offset + tc.ATTRIBUTE_IX_VALUE_TYPE] def getAttributeValueData(self, index): offset = self.getAttributeOffset(index) return self.m_attributes[offset + tc.ATTRIBUTE_IX_VALUE_DATA] def getAttributeValue(self, index): offset = self.getAttributeOffset(index) valueType = self.m_attributes[offset + tc.ATTRIBUTE_IX_VALUE_TYPE] if valueType == tc.TYPE_STRING: valueString = self.m_attributes[offset + tc.ATTRIBUTE_IX_VALUE_STRING] return self.sb.getRaw(valueString) # WIP return ""
class AXMLParser: def __init__(self, raw_buff): pass def reset(self): pass def next(self): pass def doNext(self): pass def getPrefixByUri(self, uri): pass def getPrefixByUri(self, uri): pass def getName(self): pass def getText(self): pass def getNamespacePrefix(self, pos): pass def getNamespaceUri(self, pos): pass def getNamespaceCount(self, pos): pass def getAttributeOffset(self, index): pass def getAttributeCount(self): pass def getAttributePrefix(self, index): pass def getAttributeName(self, index): pass def getAttributeValueType(self, index): pass def getAttributeValueData(self, index): pass def getAttributeValueType(self, index): pass
19
0
12
2
9
1
3
0.11
0
6
3
0
18
14
18
18
226
57
157
54
138
17
155
54
136
18
0
3
45
3,331
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/apk.py
airtest.utils.apkparser.apk.APK
class APK: """APK manages apk file format""" def __init__(self, filename): """ @param filename: specify the path of the file, or raw data @param raw: specify (boolean) if the filename is a path or raw data """ self.filename = filename self.xml = {} self.package = "" self.androidversion = {} self._permissions = [] self.valid_apk = False with open(filename, "rb") as fd: self.__raw = fd.read() self.zip = zipfile.ZipFile(filename) for i in self.zip.namelist(): if i == "AndroidManifest.xml": self.xml[i] = minidom.parseString(AXMLPrinter(self.zip.read(i)).getBuff()) self.package = self.xml[i].documentElement.getAttribute("package") self.androidversion["Code"] = self.xml[i].documentElement.getAttribute("android:versionCode") self.androidversion["Name"] = self.xml[i].documentElement.getAttribute("android:versionName") for item in self.xml[i].getElementsByTagName("uses-permission"): self._permissions.append(str(item.getAttribute("android:name"))) self.valid_apk = True def is_valid_apk(self): return self.valid_apk def get_filename(self): """ Return the filename of the APK """ return self.filename def get_package(self): """ Return the name of the package """ return self.package def get_androidversion_code(self): """ Return the android version code """ return self.androidversion["Code"] androidversion_code = property(get_androidversion_code) def get_androidversion_name(self): """ Return the android version name """ return self.androidversion["Name"] androidversion_name = property(get_androidversion_name) def get_files(self): """ Return the files inside the APK """ return self.zip.namelist() files = property(get_files) def get_files_types(self): """ Return the files inside the APK with their types (by using python-magic) """ try: import magic except ImportError: return {} l = {} builtin_magic = 0 try: getattr(magic, "Magic") except AttributeError: builtin_magic = 1 if builtin_magic: ms = magic.open(magic.MAGIC_NONE) ms.load() for i in self.get_files(): l[ i ] = ms.buffer(self.zip.read(i)) else: m = magic.Magic() for i in self.get_files(): l[ i ] = m.from_buffer(self.zip.read(i)) return l files_types = property(get_files_types) def get_raw(self): """ Return raw bytes of the APK """ return self.__raw raw = property(get_raw) def get_file(self, filename): """ Return the raw data of the specified filename """ try: return self.zip.read(filename) except KeyError: return "" def get_dex(self): """ Return the raw data of the classes dex file """ return self.get_file("classes.dex") dex = property(get_dex) def get_elements(self, tag_name, attribute): """ Return elements in xml files which match with the tag name and the specific attribute @param tag_name: a string which specify the tag name @param attribute: a string which specify the attribute """ l = [] for i in self.xml: for item in self.xml[i].getElementsByTagName(tag_name): value = item.getAttribute(attribute) if len(value) > 0: if value[0] == ".": value = self.package + value else: v_dot = value.find(".") if v_dot == 0: value = self.package + "." + value elif v_dot == -1: value = self.package + "." + value l.append(str(value)) return l def get_element(self, tag_name, attribute): """ Return element in xml files which match with the tag name and the specific attribute @param tag_name: a string which specify the tag name @param attribute: a string which specify the attribute """ l = [] for i in self.xml: for item in self.xml[i].getElementsByTagName(tag_name): value = item.getAttribute(attribute) if len(value) > 0: return value return None def get_activities(self): """ Return the android:name attribute of all activities """ return self.get_elements("activity", "android:name") activities = property(get_activities) def get_services(self): """ Return the android:name attribute of all services """ return self.get_elements("service", "android:name") services = property(get_services) def get_receivers(self): """ Return the android:name attribute of all receivers """ return self.get_elements("receiver", "android:name") receivers = property(get_receivers) def get_providers(self): """ Return the android:name attribute of all providers """ return self.get_elements("provider", "android:name") providers = property(get_providers) def get_permissions(self): """ Return permissions """ return self._permissions permissions = property(get_permissions) def get_min_sdk_version(self): """ Return the android:minSdkVersion attribute """ return self.get_element("uses-sdk", "android:minSdkVersion") min_sdk_version = property(get_min_sdk_version) def get_target_sdk_version(self): """ Return the android:targetSdkVersion attribute """ return self.get_element("uses-sdk", "android:targetSdkVersion") target_sdk_version = property(get_target_sdk_version) def get_libraries(self): """ Return the android:name attributes for libraries """ return self.get_elements("uses-library", "android:name") libraries = property(get_libraries) def show(self): print("FILES: ", self.get_files_types()) print("ACTIVITIES: ", self.get_activities()) print("SERVICES: ", self.get_services()) print("RECEIVERS: ", self.get_receivers()) print("PROVIDERS: ", self.get_providers())
class APK: '''APK manages apk file format''' def __init__(self, filename): ''' @param filename: specify the path of the file, or raw data @param raw: specify (boolean) if the filename is a path or raw data ''' pass def is_valid_apk(self): pass def get_filename(self): ''' Return the filename of the APK ''' pass def get_package(self): ''' Return the name of the package ''' pass def get_androidversion_code(self): ''' Return the android version code ''' pass def get_androidversion_name(self): ''' Return the android version name ''' pass def get_files(self): ''' Return the files inside the APK ''' pass def get_files_types(self): ''' Return the files inside the APK with their types (by using python-magic) ''' pass def get_raw(self): ''' Return raw bytes of the APK ''' pass def get_filename(self): ''' Return the raw data of the specified filename ''' pass def get_dex(self): ''' Return the raw data of the classes dex file ''' pass def get_elements(self, tag_name, attribute): ''' Return elements in xml files which match with the tag name and the specific attribute @param tag_name: a string which specify the tag name @param attribute: a string which specify the attribute ''' pass def get_elements(self, tag_name, attribute): ''' Return element in xml files which match with the tag name and the specific attribute @param tag_name: a string which specify the tag name @param attribute: a string which specify the attribute ''' pass def get_activities(self): ''' Return the android:name attribute of all activities ''' pass def get_services(self): ''' Return the android:name attribute of all services ''' pass def get_receivers(self): ''' Return the android:name attribute of all receivers ''' pass def get_providers(self): ''' Return the android:name attribute of all providers ''' pass def get_permissions(self): ''' Return permissions ''' pass def get_min_sdk_version(self): ''' Return the android:minSdkVersion attribute ''' pass def get_target_sdk_version(self): ''' Return the android:targetSdkVersion attribute ''' pass def get_libraries(self): ''' Return the android:name attributes for libraries ''' pass def show(self): pass
23
21
9
1
5
3
2
0.54
0
6
1
0
22
8
22
22
227
39
122
63
98
66
119
62
95
7
0
5
40
3,332
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/keypoint_matching_contrib.py
airtest.aircv.keypoint_matching_contrib.SIFTMatching
class SIFTMatching(KeypointMatching): """SIFT Matching.""" METHOD_NAME = "SIFT" # 日志中的方法名 # SIFT识别特征点匹配,参数设置: FLANN_INDEX_KDTREE = 0 def init_detector(self): """Init keypoint detector object.""" if check_cv_version_is_new(): try: # opencv3 >= 3.4.12 or opencv4 >=4.5.0, sift is in main repository self.detector = cv2.SIFT_create(edgeThreshold=10) except AttributeError: try: self.detector = cv2.xfeatures2d.SIFT_create(edgeThreshold=10) except: raise NoModuleError( "There is no %s module in your OpenCV environment, need contrib module!" % self.METHOD_NAME) else: # OpenCV2.x self.detector = cv2.SIFT(edgeThreshold=10) # # create FlnnMatcher object: self.matcher = cv2.FlannBasedMatcher({'algorithm': self.FLANN_INDEX_KDTREE, 'trees': 5}, dict(checks=50)) def get_keypoints_and_descriptors(self, image): """获取图像特征点和描述符.""" keypoints, descriptors = self.detector.detectAndCompute(image, None) return keypoints, descriptors def match_keypoints(self, des_sch, des_src): """Match descriptors (特征值匹配).""" # 匹配两个图片中的特征点集,k=2表示每个特征点取出2个最匹配的对应点: return self.matcher.knnMatch(des_sch, des_src, k=2)
class SIFTMatching(KeypointMatching): '''SIFT Matching.''' def init_detector(self): '''Init keypoint detector object.''' pass def get_keypoints_and_descriptors(self, image): '''获取图像特征点和描述符.''' pass def match_keypoints(self, des_sch, des_src): '''Match descriptors (特征值匹配).''' pass
4
4
9
0
6
2
2
0.48
1
3
1
0
3
2
3
19
36
6
21
9
17
10
19
9
15
4
2
3
6
3,333
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/keypoint_matching_contrib.py
airtest.aircv.keypoint_matching_contrib.BRIEFMatching
class BRIEFMatching(KeypointMatching): """FastFeature Matching.""" METHOD_NAME = "BRIEF" # 日志中的方法名 def init_detector(self): """Init keypoint detector object.""" # BRIEF is a feature descriptor, recommand CenSurE as a fast detector: if check_cv_version_is_new(): # OpenCV3/4, star/brief is in contrib module, you need to compile it seperately. try: self.star_detector = cv2.xfeatures2d.StarDetector_create() self.brief_extractor = cv2.xfeatures2d.BriefDescriptorExtractor_create() except: import traceback traceback.print_exc() print("to use %s, you should build contrib with opencv3.0" % self.METHOD_NAME) raise NoModuleError("There is no %s module in your OpenCV environment !" % self.METHOD_NAME) else: # OpenCV2.x self.star_detector = cv2.FeatureDetector_create("STAR") self.brief_extractor = cv2.DescriptorExtractor_create("BRIEF") # create BFMatcher object: self.matcher = cv2.BFMatcher(cv2.NORM_L1) # cv2.NORM_L1 cv2.NORM_L2 cv2.NORM_HAMMING(not useable) def get_keypoints_and_descriptors(self, image): """获取图像特征点和描述符.""" # find the keypoints with STAR kp = self.star_detector.detect(image, None) # compute the descriptors with BRIEF keypoints, descriptors = self.brief_extractor.compute(image, kp) return keypoints, descriptors def match_keypoints(self, des_sch, des_src): """Match descriptors (特征值匹配).""" # 匹配两个图片中的特征点集,k=2表示每个特征点取出2个最匹配的对应点: return self.matcher.knnMatch(des_sch, des_src, k=2)
class BRIEFMatching(KeypointMatching): '''FastFeature Matching.''' def init_detector(self): '''Init keypoint detector object.''' pass def get_keypoints_and_descriptors(self, image): '''获取图像特征点和描述符.''' pass def match_keypoints(self, des_sch, des_src): '''Match descriptors (特征值匹配).''' pass
4
4
10
0
7
4
2
0.59
1
1
1
0
3
3
3
19
38
5
22
11
17
13
21
11
16
3
2
2
5
3,334
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/keypoint_matching.py
airtest.aircv.keypoint_matching.ORBMatching
class ORBMatching(KeypointMatching): """ORB Matching.""" METHOD_NAME = "ORB" # 日志中的方法名 def init_detector(self): """Init keypoint detector object.""" self.detector = cv2.ORB_create() # create BFMatcher object: self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING)
class ORBMatching(KeypointMatching): '''ORB Matching.''' def init_detector(self): '''Init keypoint detector object.''' pass
2
2
5
0
3
3
1
1
1
0
0
0
1
2
1
17
10
2
5
5
3
5
5
5
3
1
2
0
1
3,335
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/keypoint_matching.py
airtest.aircv.keypoint_matching.KAZEMatching
class KAZEMatching(KeypointMatching): """KAZE Matching.""" pass
class KAZEMatching(KeypointMatching): '''KAZE Matching.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
16
4
1
2
1
1
1
2
1
1
0
2
0
0
3,336
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_ios_mjpeg.py
tests.test_ios_mjpeg.TestIosMjpeg
class TestIosMjpeg(unittest.TestCase): @classmethod def setUpClass(cls): cls.ios = IOS(DEFAULT_ADDR, cap_method=CAP_METHOD.MJPEG, mjpeg_port=DEFAULT_PORT) cls.mjpeg_server = cls.ios.mjpegcap @classmethod def tearDownClass(cls): try_remove('screen.png') cls.mjpeg_server.teardown_stream() def test_get_frame(self): for i in range(5): data = self.mjpeg_server.get_frame() filename = "./screen.jpg" with open(filename, "wb") as f: f.write(data) self.assertTrue(os.path.exists(filename)) time.sleep(2) def test_snapshot(self): # 测试截图,可以手动将设备横屏后再运行确认截图的方向是否正确 # mjpeg直接截图,可能图像不是最新的 for i in range(3): screen = self.mjpeg_server.snapshot(ensure_orientation=True) aircv.show(screen) time.sleep(2) def test_frame_resume(self): """ 用于测试当连接建立一段时间后,暂停接受数据,然后恢复数据的效果 Returns: """ import cv2 for i in range(20): data = self.mjpeg_server.get_frame_from_stream() img = aircv.utils.string_2_img(data) cv2.imshow("test", img) c = cv2.waitKey(10) time.sleep(0.05) time.sleep(10) for i in range(200): data = self.mjpeg_server.get_frame_from_stream() img = aircv.utils.string_2_img(data) cv2.imshow("test", img) c = cv2.waitKey(10) time.sleep(0.05) cv2.destroyAllWindows() def test_get_blank_screen(self): img_string = self.mjpeg_server.get_blank_screen() img = aircv.utils.string_2_img(img_string) aircv.show(img) def test_teardown_stream(self): self.mjpeg_server.get_frame() if self.mjpeg_server.port_forwarding is True: self.assertTrue(is_port_open(self.mjpeg_server.ip, self.mjpeg_server.port)) self.mjpeg_server.teardown_stream() self.assertFalse(is_port_open(self.mjpeg_server.ip, self.mjpeg_server.port))
class TestIosMjpeg(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_get_frame(self): pass def test_snapshot(self): pass def test_frame_resume(self): ''' 用于测试当连接建立一段时间后,暂停接受数据,然后恢复数据的效果 Returns: ''' pass def test_get_blank_screen(self): pass def test_teardown_stream(self): pass
10
1
7
0
6
1
2
0.13
1
3
2
0
5
0
7
79
61
7
48
23
37
6
46
20
37
3
2
2
12
3,337
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_ios_instruct_cmd.py
tests.test_ios_instruct_cmd.TestInstructCmd
class TestInstructCmd(unittest.TestCase): @classmethod def setUpClass(cls): cls.ios = IOS(DEFAULT_ADDR) cls.ihelper = cls.ios.instruct_helper @classmethod def tearDownClass(cls): pass def tearDown(self): self.ihelper.tear_down() def test_setup_proxy(self): port, _ = self.ihelper.setup_proxy(9100) self.assertTrue(is_port_open('localhost', port)) def test_remove_proxy(self): port, _ = self.ihelper.setup_proxy(9100) self.assertTrue(is_port_open('localhost', port)) time.sleep(2) self.ihelper.remove_proxy(port) time.sleep(2) self.assertFalse(is_port_open('localhost', port)) def test_do_proxy_usbmux(self): # 仅当连接本地usb设备时才可用 self.assertFalse(is_port_open('localhost', 9100)) time.sleep(1) self.ihelper.do_proxy_usbmux(9100, 9100) time.sleep(5) self.assertTrue(is_port_open('localhost', 9100)) def test_do_proxy(self): self.assertFalse(is_port_open('localhost', 9101)) time.sleep(1) self.ihelper.do_proxy(9101, 9100) time.sleep(5) self.assertTrue(is_port_open('localhost', 9101)) def test_do_proxy2(self): self.ihelper.do_proxy(9101, 9100) time.sleep(3) self.ihelper.remove_proxy(9101) def test_tear_down(self): port, _ = self.ihelper.setup_proxy(9100) self.assertTrue(is_port_open('localhost', port)) self.ihelper.tear_down() time.sleep(3) self.assertFalse(is_port_open('localhost', port))
class TestInstructCmd(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def tearDownClass(cls): pass def test_setup_proxy(self): pass def test_remove_proxy(self): pass def test_do_proxy_usbmux(self): pass def test_do_proxy_usbmux(self): pass def test_do_proxy2(self): pass def test_tear_down(self): pass
12
0
4
0
4
0
1
0.02
1
1
1
0
7
0
9
81
51
8
42
15
30
1
40
13
30
1
2
0
9
3,338
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_cli.py
tests.test_cli.TestCli
class TestCli(unittest.TestCase): @classmethod def setUpClass(cls): if not ADB().devices(state="device"): raise RuntimeError("At lease one adb device required") @classmethod def tearDownClass(cls): G.LOGGER.set_logfile(None) try_remove(OUTPUT_HTML) def test_info(self): argv = ["info", OWL] main_parser(argv) def test_run_android(self): argv = ["run", OWL, "--device", "Android:///", "--log"] main_parser(argv) # test_report(self): try_remove(OUTPUT_HTML) argv = ["report", OWL] main_parser(argv) self.assertTrue(os.path.exists(OUTPUT_HTML)) def test_report_with_log_dir(self): try_remove(OUTPUT_HTML) argv = ["run", OWL, "--device", "Android:///", "--log", DIR("./logs")] main_parser(argv) argv = ["report", OWL, "--log_root", DIR(".")] main_parser(argv) self.assertTrue(os.path.exists(OUTPUT_HTML))
class TestCli(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_info(self): pass def test_run_android(self): pass def test_report_with_log_dir(self): pass
8
0
5
0
5
0
1
0.04
1
3
2
0
3
0
5
77
33
6
26
11
18
1
24
9
18
2
2
1
6
3,339
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_aircv.py
tests.test_aircv.TestAircv
class TestAircv(unittest.TestCase): """Test aircv.""" # 2960*1440设备 内存耗费: kaze (2GB) >> sift > akaze >> surf > brisk > brief > orb > tpl # 单纯效果,推荐程度: tpl > surf ≈ sift > kaze > brisk > akaze> brief > orb # 有限内存,推荐程度: tpl > surf > sift > brisk > akaze > brief > orb >kaze THRESHOLD = 0.7 RGB = True @classmethod def setUpClass(cls): cls.keypoint_sch = imread("matching_images/keypoint_search.png") cls.keypoint_src = imread("matching_images/keypoint_screen.png") cls.template_sch = imread("matching_images/template_search.png") cls.template_src = imread("matching_images/template_screen.png") @classmethod def tearDownClass(cls): pass def test_find_template(self): """Template matching.""" result = TemplateMatching(self.template_sch, self.template_src, threshold=self.THRESHOLD, rgb=self.RGB).find_best_result() self.assertIsInstance(result, dict) def test_find_all_template(self): """Template matching.""" result = TemplateMatching(self.template_sch, self.template_src, threshold=self.THRESHOLD, rgb=self.RGB).find_all_results() self.assertIsInstance(result, list) def test_find_kaze(self): """KAZE matching.""" # 较慢,稍微稳定一点. result = KAZEMatching(self.keypoint_sch, self.keypoint_src, threshold=self.THRESHOLD, rgb=self.RGB).find_best_result() self.assertIsInstance(result, dict) def test_find_brisk(self): """BRISK matching.""" # 快,效果一般,不太稳定 result = BRISKMatching(self.keypoint_sch, self.keypoint_src, threshold=self.THRESHOLD, rgb=self.RGB).find_best_result() self.assertIsInstance(result, dict) def test_find_akaze(self): """AKAZE matching.""" # 较快,效果较差,很不稳定 result = AKAZEMatching(self.keypoint_sch, self.keypoint_src, threshold=self.THRESHOLD, rgb=self.RGB).find_best_result() self.assertIsInstance(result, dict) def test_find_orb(self): """ORB matching.""" # 很快,效果垃圾 result = ORBMatching(self.keypoint_sch, self.keypoint_src, threshold=self.THRESHOLD, rgb=self.RGB).find_best_result() self.assertIsInstance(result, dict) def test_contrib_find_sift(self): """SIFT matching (----need OpenCV contrib module----).""" # 慢,最稳定 result = SIFTMatching(self.keypoint_sch, self.keypoint_src, threshold=self.THRESHOLD, rgb=self.RGB).find_best_result() self.assertIsInstance(result, dict) def test_contrib_find_surf(self): """SURF matching (----need OpenCV contrib module----).""" # 快,效果不错 result = SURFMatching(self.keypoint_sch, self.keypoint_src, threshold=self.THRESHOLD, rgb=self.RGB).find_best_result() self.assertIsInstance(result, dict) def test_contrib_find_brief(self): """BRIEF matching (----need OpenCV contrib module----).""" # 识别特征点少,只适合强特征图像的匹配 result = BRIEFMatching(self.keypoint_sch, self.keypoint_src, threshold=self.THRESHOLD, rgb=self.RGB).find_best_result() self.assertIsInstance(result, dict) def test_contrib_func_find_sift(self): """Test find_sift function in sift.py.""" result = find_sift(self.keypoint_src, self.keypoint_sch, threshold=self.THRESHOLD, rgb=self.RGB) self.assertIsInstance(result, dict) def test_func_find_template(self): """Test find_template function in template.py.""" result = find_template(self.template_src, self.template_sch, threshold=self.THRESHOLD, rgb=self.RGB) self.assertIsInstance(result, dict) def test_func_find_all_template(self): """Test find_all_template function in template.py.""" result = find_all_template(self.template_src, self.template_sch, threshold=self.THRESHOLD, rgb=self.RGB) self.assertIsInstance(result, list)
class TestAircv(unittest.TestCase): '''Test aircv.''' @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_find_template(self): '''Template matching.''' pass def test_find_all_template(self): '''Template matching.''' pass def test_find_kaze(self): '''KAZE matching.''' pass def test_find_brisk(self): '''BRISK matching.''' pass def test_find_akaze(self): '''AKAZE matching.''' pass def test_find_orb(self): '''ORB matching.''' pass def test_contrib_find_sift(self): '''SIFT matching (----need OpenCV contrib module----).''' pass def test_contrib_find_surf(self): '''SURF matching (----need OpenCV contrib module----).''' pass def test_contrib_find_brief(self): '''BRIEF matching (----need OpenCV contrib module----).''' pass def test_contrib_func_find_sift(self): '''Test find_sift function in sift.py.''' pass def test_func_find_template(self): '''Test find_template function in template.py.''' pass def test_func_find_all_template(self): '''Test find_all_template function in template.py.''' pass
17
13
5
0
3
1
1
0.48
1
10
8
0
12
4
14
86
88
17
48
31
31
23
46
29
31
1
2
0
14
3,340
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_android.py
tests.test_android.TestAndroid
class TestAndroid(unittest.TestCase): @classmethod def setUpClass(self): self.android = Android() @classmethod def tearDownClass(self): try_remove('screen.mp4') def _install_test_app(self): if PKG not in self.android.list_app(): self.android.install_app(APK) def test_serialno(self): self.assertIsNotNone(self.android.serialno) def test_adb(self): self.assertIsInstance(self.android.adb, ADB) def test_display_info(self): self.assertIsInstance(self.android.adb.display_info, dict) print(self.android.display_info) self.assertIn("width", self.android.display_info) self.assertIn("height", self.android.display_info) self.assertIn("orientation", self.android.display_info) self.assertIn("rotation", self.android.display_info) def test_minicap(self): minicap = self.android.minicap self.assertIsInstance(minicap, Minicap) self.assertIs(minicap.adb.display_info, self.android.display_info) def test_minitouch(self): self.assertIsInstance(self.android.minitouch, Minitouch) def test_list_app(self): self._install_test_app() self.assertIn(PKG, self.android.list_app()) self.assertIn(PKG, self.android.list_app(third_only=True)) def test_path_app(self): self._install_test_app() app_path = self.android.path_app(PKG) self.assertIn(PKG, app_path) self.assertTrue(app_path.startswith("/")) with self.assertRaises(AirtestError): self.android.path_app('com.netease.this.is.error') def test_check_app(self): self._install_test_app() self.assertTrue(self.android.check_app(PKG)) with self.assertRaises(AirtestError): self.android.check_app('com.netease.this.is.error') def test_snapshot(self): self._install_test_app() for i in (CAP_METHOD.ADBCAP, CAP_METHOD.MINICAP, CAP_METHOD.JAVACAP): filename = "./screen.png" if os.path.exists(filename): os.remove(filename) self.android.cap_method = i self.android.wake() screen = self.android.snapshot(filename=filename) self.assertIsInstance(screen, numpy.ndarray) self.assertTrue(os.path.exists(filename)) os.remove(filename) def test_snapshot_thread(self): def assert_exists_and_remove(filename): self.assertTrue(os.path.exists(filename)) os.remove(filename) class ScreenshotThread(Thread): def __init__(self, dev, assert_true): self.dev = dev self._running = True self.assert_true = assert_true super(ScreenshotThread, self).__init__() self.dev.snapshot("screen_thread.jpg") assert_exists_and_remove("screen_thread.jpg") def terminate(self): self._running = False def run(self): while self._running: filename = "screen_thread.jpg" self.dev.snapshot(filename) assert_exists_and_remove(filename) time.sleep(2) task = ScreenshotThread(self.android, self.assertTrue) task.daemon = True task.start() for i in range(10): self.android.snapshot("screen.jpg") assert_exists_and_remove("screen.jpg") time.sleep(2) task.terminate() def test_shell(self): self.assertEqual(self.android.shell('echo nimei').strip(), 'nimei') def test_keyevent(self): self.android.keyevent("BACK") def test_wake(self): self.android.wake() def test_screenon(self): self.assertIn(self.android.is_screenon(), (True, False)) def test_home(self): self.android.home() def test_text(self): self.android.ime_method = IME_METHOD.ADBIME self.android.text('test text') self.android.ime_method = IME_METHOD.YOSEMITEIME self.android.text(u'你好') def test_clipboard(self): for i in range(10): text1 = "test clipboard" + str(i) self.android.set_clipboard(text1) self.assertEqual(self.android.get_clipboard(), text1) self.android.paste() self.android.paste() # test escape special char text2 = "test clipboard with $pecial char #@!#%$#^&*()'" self.android.set_clipboard(text2) self.assertEqual(self.android.get_clipboard(), text2) self.android.paste() def test_touch(self): for i in (TOUCH_METHOD.ADBTOUCH, TOUCH_METHOD.MINITOUCH, TOUCH_METHOD.MAXTOUCH): self.android.touch_method = i self.android.touch((100, 100)) def test_touch_percentage(self): for i in (TOUCH_METHOD.ADBTOUCH, TOUCH_METHOD.MINITOUCH, TOUCH_METHOD.MAXTOUCH): self.android.touch_method = i self.android.touch((0.5, 0.5)) time.sleep(2) self.android.keyevent("BACK") def test_swipe(self): for i in (TOUCH_METHOD.ADBTOUCH, TOUCH_METHOD.MINITOUCH, TOUCH_METHOD.MAXTOUCH): self.android.touch_method = i self.android.swipe((100, 100), (300, 300)) self.android.swipe((100, 100), (300, 300), fingers=1) self.android.swipe((100, 100), (300, 300), fingers=2) self.android.touch_method = TOUCH_METHOD.ADBTOUCH self.android.swipe((100, 100), (300, 300), fingers=3) self.android.touch_method = TOUCH_METHOD.MINITOUCH with self.assertRaises(Exception): self.android.swipe((100, 100), (300, 300), fingers=3) def test_swipe_percentage(self): for i in (TOUCH_METHOD.ADBTOUCH, TOUCH_METHOD.MINITOUCH, TOUCH_METHOD.MAXTOUCH): self.android.touch_method = i self.android.swipe((0.6, 0.5), (0.4, 0.5)) self.android.swipe((0.3, 0.5), (0.6, 0.5), fingers=1) self.android.swipe((0.1, 0.1), (0.3, 0.3), fingers=2) with self.assertRaises(Exception): self.android.swipe((0.1, 0.1), (0.3, 0.3), fingers=3) def test_get_top_activity(self): self._install_test_app() self.android.start_app(PKG) pkg, activity, pid = self.android.get_top_activity() self.assertEqual(pkg, PKG) self.assertEqual(activity, 'org.cocos2dx.javascript.AppActivity') self.assertIsInstance(int(pid), int) def test_is_keyboard_shown(self): self.android.is_keyboard_shown() def test_is_locked(self): self.android.is_locked() def test_unlock(self): self.android.unlock() def test_pinch(self): for i in (TOUCH_METHOD.MINITOUCH, TOUCH_METHOD.MAXTOUCH): self.android.touch_method = i self.android.pinch(in_or_out='in') self.android.pinch(in_or_out='out') self.android.touch_method = TOUCH_METHOD.ADBTOUCH with self.assertRaises(Exception): self.android.pinch(in_or_out='in') def test_swipe_along(self): coordinates_list = [(100, 300), (300, 300), (100, 500), (300, 600)] for i in (TOUCH_METHOD.MINITOUCH, TOUCH_METHOD.MAXTOUCH): self.android.touch_method = i self.android.swipe_along(coordinates_list) self.android.swipe_along(coordinates_list, duration=3, steps=10) self.android.touch_method = TOUCH_METHOD.ADBTOUCH with self.assertRaises(Exception): self.android.swipe_along(coordinates_list) def test_swipe_along_percentage(self): coordinates_list = [(0.1, 0.3), (0.7, 0.3), (0.1, 0.7), (0.8, 0.8)] for i in (TOUCH_METHOD.MINITOUCH, TOUCH_METHOD.MAXTOUCH): self.android.touch_method = i self.android.swipe_along(coordinates_list) self.android.swipe_along(coordinates_list, duration=3, steps=10) self.android.touch_method = TOUCH_METHOD.ADBTOUCH with self.assertRaises(Exception): self.android.swipe_along(coordinates_list) def test_two_finger_swipe(self): for i in (TOUCH_METHOD.MINITOUCH, TOUCH_METHOD.MAXTOUCH): self.android.touch_method = i self.android.two_finger_swipe((100, 100), (200, 200)) self.android.two_finger_swipe((100, 100), (200, 200), duration=3, steps=10) self.android.two_finger_swipe((100, 100), (200, 200), offset=(-20, 100)) self.android.two_finger_swipe((100, 100), (200, 200), offset=(-1000, 100)) self.android.touch_method = TOUCH_METHOD.ADBTOUCH with self.assertRaises(Exception): self.android.two_finger_swipe((100, 100), (200, 200)) def test_two_findger_swipe_percentage(self): for i in (TOUCH_METHOD.MINITOUCH, TOUCH_METHOD.MAXTOUCH): self.android.touch_method = i self.android.two_finger_swipe((0.1, 0.1), (0.2, 0.2)) self.android.two_finger_swipe((0.1, 0.1), (0.2, 0.2), duration=3, steps=10) self.android.two_finger_swipe((0.1, 0.1), (0.2, 0.2), offset=(-0.02, 0.1)) self.android.two_finger_swipe((0.1, 0.1), (0.2, 0.2), offset=(-0.2, 0.1)) self.android.touch_method = TOUCH_METHOD.ADBTOUCH with self.assertRaises(Exception): self.android.two_finger_swipe((0.1, 0.1), (0.2, 0.2)) def test_disconnect(self): self.android.snapshot() self.android.touch((100, 100)) self.android.disconnect() # 检查是否将所有forward的端口都断开了 self.assertEqual(len(self.android.adb._forward_local_using), 0) # 断开后,如果再次连接也仍然可以正常使用,并且要正确地在退出时进行清理(检查log中没有warning) self.android.snapshot() self.assertEqual(len(self.android.adb._forward_local_using), 1)
class TestAndroid(unittest.TestCase): @classmethod def setUpClass(self): pass @classmethod def tearDownClass(self): pass def _install_test_app(self): pass def test_serialno(self): pass def test_adb(self): pass def test_display_info(self): pass def test_minicap(self): pass def test_minitouch(self): pass def test_list_app(self): pass def test_path_app(self): pass def test_check_app(self): pass def test_snapshot(self): pass def test_snapshot_thread(self): pass def assert_exists_and_remove(filename): pass class ScreenshotThread(Thread): def __init__(self, dev, assert_true): pass def terminate(self): pass def run(self): pass def test_shell(self): pass def test_keyevent(self): pass def test_wake(self): pass def test_screenon(self): pass def test_home(self): pass def test_text(self): pass def test_clipboard(self): pass def test_touch(self): pass def test_touch_percentage(self): pass def test_swipe(self): pass def test_swipe_percentage(self): pass def test_get_top_activity(self): pass def test_is_keyboard_shown(self): pass def test_is_locked(self): pass def test_unlock(self): pass def test_pinch(self): pass def test_swipe_along(self): pass def test_swipe_along_percentage(self): pass def test_two_finger_swipe(self): pass def test_two_findger_swipe_percentage(self): pass def test_disconnect(self): pass
42
0
6
0
6
0
1
0.02
1
14
9
0
32
1
34
106
255
48
204
69
162
4
202
67
162
3
2
2
53
3,341
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_android_recorder.py
tests.test_android_recorder.TestAndroidFfmpegRecorder
class TestAndroidFfmpegRecorder(unittest.TestCase): """Test Android ffmpeg screen recording function""" @classmethod def setUpClass(cls): cls.android = Android() def tearDown(self): try_remove("screen.mp4") def test_recording(self): save_path = self.android.start_recording(mode='ffmpeg', output="screen.mp4", max_time=10) time.sleep(10) self.android.stop_recording() self.assertTrue(os.path.exists(save_path)) def test_maxsize(self): save_path = self.android.start_recording(mode='ffmpeg', output="screen.mp4", max_time=10, max_size=720) time.sleep(10) self.android.stop_recording() self.assertTrue(os.path.exists(save_path)) def test_maxsize_error(self): for maxsize in [0, "test", "800*600"]: save_path = self.android.start_recording(mode='ffmpeg', output="screen.mp4", max_time=10, max_size=maxsize) time.sleep(10) self.android.stop_recording() self.assertTrue(os.path.exists(save_path)) try_remove(save_path) def test_ori(self): for ori in ["portrait", 1, "landscape", 2, 0]: save_path = self.android.start_recording(mode='ffmpeg', output="screen.mp4", orientation=ori) time.sleep(10) self.android.stop_recording() self.assertTrue(os.path.exists(save_path)) def test_ori_error(self): # 当orientation不合法时,会自动使用0,即方形录制 for ori in ["p", "1"]: save_path = self.android.start_recording(mode='ffmpeg', output="screen.mp4", orientation=ori) time.sleep(10) self.android.stop_recording() self.assertTrue(os.path.exists(save_path)) def test_fps(self): for fps in [1, 10, 30, 60]: save_path = self.android.start_recording(mode='ffmpeg', output="screen.mp4", fps=fps) time.sleep(10) self.android.stop_recording() self.assertTrue(os.path.exists(save_path))
class TestAndroidFfmpegRecorder(unittest.TestCase): '''Test Android ffmpeg screen recording function''' @classmethod def setUpClass(cls): pass def tearDown(self): pass def test_recording(self): pass def test_maxsize(self): pass def test_maxsize_error(self): pass def test_ori(self): pass def test_ori_error(self): pass def test_fps(self): pass
10
1
5
0
5
0
2
0.05
1
1
1
0
7
0
8
80
50
7
41
20
31
2
40
19
31
2
2
1
12
3,342
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_assertions.py
tests.test_assertions.TestAssertionsOnAndroid
class TestAssertionsOnAndroid(unittest.TestCase): @classmethod def setUpClass(cls): cls.LOG_DIR = DIR(DEFAULT_LOG_DIR) if not isinstance(G.DEVICE, Android): connect_device("Android:///") cls.dev = G.DEVICE ST.LOG_DIR = cls.LOG_DIR def setUp(self): try_remove(self.LOG_DIR) try: os.mkdir(self.LOG_DIR) except FileExistsError: pass def tearDown(self): try_remove(self.LOG_DIR) def _start_apk_main_scene(self): if PKG not in self.dev.list_app(): install(APK) stop_app(PKG) start_app(PKG) def test_assert_exists(self): self._start_apk_main_scene() assert_exists(TPL) with self.assertRaises(AssertionError): assert_exists(TPL2) stop_app(PKG) def test_assert_not_exists(self): self._start_apk_main_scene() assert_not_exists(TPL2) with self.assertRaises(AssertionError): assert_not_exists(TPL) stop_app(PKG) def test_assert_equal(self): with self.assertRaises(AssertionError): assert_equal(1, 2) assert_equal(1+1, 2, snapshot=False) self.assertEqual(len(os.listdir(self.LOG_DIR)), 1, "snapshot should be saved only once") def test_assert_not_equal(self): with self.assertRaises(AssertionError): assert_not_equal(1, 1, "assert not equal") assert_not_equal(1, 2) self.assertEqual(len(os.listdir(self.LOG_DIR)), 2) def test_assert_true(self): # bool(expr) is True assert_true(True) assert_true(1 == 1) assert_true("123") assert_true("FOO".isupper()) with self.assertRaises(AssertionError): assert_true("", "msg") with self.assertRaises(AssertionError): assert_true(None) with self.assertRaises(AssertionError): assert_true(1 == 2, snapshot=False) self.assertEqual(len(os.listdir(self.LOG_DIR)), 6) def test_assert_false(self): # bool(expr) is False assert_false(False) assert_false(1==2) assert_false(None) assert_false([]) with self.assertRaises(AssertionError): assert_false(1==1) self.assertEqual(len(os.listdir(self.LOG_DIR)), 5) def test_assert_is(self): assert_is(TPL, TPL) assert_is(1, 1) with self.assertRaises(AssertionError): assert_is(1, 2) with self.assertRaises(AssertionError): assert_is(1, "1") self.assertEqual(len(os.listdir(self.LOG_DIR)), 4) def test_assert_is_not(self): assert_is_not(TPL, TPL2) assert_is_not(1, 2) assert_is_not(1, "1") with self.assertRaises(AssertionError): assert_is_not(1, 1) self.assertEqual(len(os.listdir(self.LOG_DIR)), 4) def test_assert_is_none(self): assert_is_none(None) with self.assertRaises(AssertionError): assert_is_none(1) with self.assertRaises(AssertionError): assert_is_none([]) self.assertEqual(len(os.listdir(self.LOG_DIR)), 3) def test_assert_is_not_none(self): assert_is_not_none(1, snapshot=False) assert_is_not_none(self.dev) with self.assertRaises(AssertionError): assert_is_not_none(None) self.assertEqual(len(os.listdir(self.LOG_DIR)), 2) def test_assert_in(self): assert_in(TPL, [TPL, TPL2]) with self.assertRaises(AssertionError): assert_in(3, [1, 2]) self.assertEqual(len(os.listdir(self.LOG_DIR)), 2) def test_assert_not_in(self): assert_not_in(3, [1, 2]) with self.assertRaises(AssertionError): assert_not_in(TPL, [TPL, TPL2]) self.assertEqual(len(os.listdir(self.LOG_DIR)), 2) def test_assert_is_instance(self): assert_is_instance(TPL, Template) with self.assertRaises(AssertionError): assert_is_instance(1, str) assert_is_instance(1, type(2)) self.assertEqual(len(os.listdir(self.LOG_DIR)), 3) def test_assert_not_is_instance(self): assert_not_is_instance(1, str) with self.assertRaises(AssertionError): assert_not_is_instance(TPL, Template) self.assertEqual(len(os.listdir(self.LOG_DIR)), 2) def test_assert_greater(self): assert_greater(2, 1) with self.assertRaises(AssertionError): assert_greater(1, 1) self.assertEqual(len(os.listdir(self.LOG_DIR)), 2) def test_assert_greater_equal(self): assert_greater_equal(2, 1) assert_greater_equal(1, 1) with self.assertRaises(AssertionError): assert_greater_equal(1, 2) self.assertEqual(len(os.listdir(self.LOG_DIR)), 3) def test_assert_less(self): assert_less(1, 2) with self.assertRaises(AssertionError): assert_less(1, 1) self.assertEqual(len(os.listdir(self.LOG_DIR)), 2) def test_assert_less_equal(self): assert_less_equal(1, 2) assert_less_equal(1, 1) with self.assertRaises(AssertionError): assert_less_equal(2, 1) self.assertEqual(len(os.listdir(self.LOG_DIR)), 3)
class TestAssertionsOnAndroid(unittest.TestCase): @classmethod def setUpClass(cls): pass def setUpClass(cls): pass def tearDown(self): pass def _start_apk_main_scene(self): pass def test_assert_exists(self): pass def test_assert_not_exists(self): pass def test_assert_equal(self): pass def test_assert_not_equal(self): pass def test_assert_true(self): pass def test_assert_false(self): pass def test_assert_is(self): pass def test_assert_is_not(self): pass def test_assert_is_none(self): pass def test_assert_is_not_none(self): pass def test_assert_in(self): pass def test_assert_not_in(self): pass def test_assert_is_instance(self): pass def test_assert_not_is_instance(self): pass def test_assert_greater(self): pass def test_assert_greater_equal(self): pass def test_assert_less(self): pass def test_assert_less_equal(self): pass
24
0
7
1
6
0
1
0.01
1
8
4
0
21
0
22
94
181
45
134
24
110
2
133
23
110
2
2
1
25
3,343
AirtestProject/Airtest
AirtestProject_Airtest/airtest/report/report.py
airtest.report.report.LogToHtml
class LogToHtml(object): """Convert log to html display """ scale = 0.5 def __init__(self, script_root, log_root="", static_root="", export_dir=None, script_name="", logfile=None, lang="en", plugins=None): self.log = [] self.devices = {} self.script_root = script_root self.script_name = script_name if not self.script_name or os.path.isfile(self.script_root): self.script_root, self.script_name = script_dir_name(self.script_root) self.log_root = log_root or ST.LOG_DIR or os.path.join(".", DEFAULT_LOG_DIR) self.static_root = static_root or STATIC_DIR self.test_result = True self.run_start = None self.run_end = None self.export_dir = export_dir self.logfile = logfile or getattr(ST, "LOG_FILE", DEFAULT_LOG_FILE) self.lang = lang self.init_plugin_modules(plugins) @staticmethod def init_plugin_modules(plugins): if not plugins: return for plugin_name in plugins: LOGGING.debug("try loading plugin: %s" % plugin_name) try: __import__(plugin_name) except: LOGGING.error(traceback.format_exc()) def _load(self): logfile = os.path.join(self.log_root, self.logfile) if not PY3: logfile = logfile.encode(sys.getfilesystemencoding()) with io.open(logfile, encoding="utf-8") as f: for line in f.readlines(): self.log.append(json.loads(line)) def _analyse(self): """ 解析log成可渲染的dict """ steps = [] children_steps = [] for log in self.log: depth = log['depth'] if not self.run_start: self.run_start = log.get('data', {}).get('start_time', '') or log["time"] self.run_end = log["time"] if depth == 0: # single log line, not in stack steps.append(log) elif depth == 1: step = deepcopy(log) step["__children__"] = children_steps steps.append(step) children_steps = [] else: children_steps.insert(0, log) translated_steps = [self._translate_step(s) for s in steps] if len(translated_steps) > 0 and translated_steps[-1].get("traceback"): # Final Error self.test_result = False return translated_steps def _translate_step(self, step): """translate single step""" name = step["data"]["name"] title = self._translate_title(name, step) code = self._translate_code(step) desc = self._translate_desc(step, code) screen = self._translate_screen(step, code) info = self._translate_info(step) assertion = self._translate_assertion(step) self._translate_device(step) translated = { "title": title, "time": step["time"], "code": code, "screen": screen, "desc": desc, "traceback": info[0], "log": info[1], "assert": assertion, } return translated def _translate_assertion(self, step): if "assert_" in step["data"].get("name", "") and "msg" in step["data"].get("call_args", {}): return step["data"]["call_args"]["msg"] def _translate_screen(self, step, code): if step['tag'] not in ["function", "info"] or not step.get("__children__"): return None screen = { "src": None, "rect": [], "pos": [], "vector": [], "confidence": None, } for item in step["__children__"]: if item["data"]["name"] == "try_log_screen": snapshot = item["data"].get("ret", None) if isinstance(snapshot, six.text_type): src = snapshot elif isinstance(snapshot, dict): src = snapshot['screen'] screen['resolution'] = snapshot['resolution'] else: continue if self.export_dir: # all relative path screen['_filepath'] = os.path.join(DEFAULT_LOG_DIR, src) else: screen['_filepath'] = os.path.abspath(os.path.join(self.log_root, src)) screen['src'] = screen['_filepath'] self.get_thumbnail(os.path.join(self.log_root, src)) screen['thumbnail'] = self.get_small_name(screen['src']) break display_pos = None for item in step["__children__"]: if item["data"]["name"] == "_cv_match" and isinstance(item["data"].get("ret"), dict): cv_result = item["data"]["ret"] pos = cv_result['result'] if self.is_pos(pos): display_pos = [round(pos[0]), round(pos[1])] rect = self.div_rect(cv_result['rectangle']) screen['rect'].append(rect) screen['confidence'] = cv_result['confidence'] break if step["data"]["name"] in ["touch", "assert_exists", "wait", "exists"]: # 将图像匹配得到的pos修正为最终pos if self.is_pos(step["data"].get("ret")): display_pos = step["data"]["ret"] elif self.is_pos(step["data"]["call_args"].get("v")): display_pos = step["data"]["call_args"]["v"] elif step["data"]["name"] == "swipe": if "ret" in step["data"]: screen["pos"].append(step["data"]["ret"][0]) target_pos = step["data"]["ret"][1] origin_pos = step["data"]["ret"][0] screen["vector"].append([target_pos[0] - origin_pos[0], target_pos[1] - origin_pos[1]]) if display_pos: screen["pos"].append(display_pos) return screen def _translate_device(self, step): if step["tag"] == "function" and step["data"]["name"] == "connect_device": uri = step["data"]["call_args"]["uri"] platform, uuid, params = parse_device_uri(uri) if "name" in params: uuid = params["name"] if uuid not in self.devices: self.devices[uuid] = uri return uuid return None @classmethod def get_thumbnail(cls, path): """compress screenshot""" new_path = cls.get_small_name(path) if not os.path.isfile(new_path): try: img = Image.open(path) compress_image(img, new_path, ST.SNAPSHOT_QUALITY, max_size=300) except Exception: LOGGING.error(traceback.format_exc()) return new_path else: return None @classmethod def get_small_name(cls, filename): name, ext = os.path.splitext(filename) return "%s_small%s" % (name, ext) def _translate_info(self, step): trace_msg, log_msg = "", "" if "traceback" in step["data"]: # 若包含有traceback内容,将会认定步骤失败 trace_msg = step["data"]["traceback"] if step["tag"] == "info": if "log" in step["data"]: # 普通文本log内容,仅显示 log_msg = step["data"]["log"] return trace_msg, log_msg def _translate_code(self, step): if step["tag"] != "function": return None step_data = step["data"] args = [] code = { "name": step_data["name"], "args": args, } for key, value in step_data["call_args"].items(): args.append({ "key": key, "value": value, }) for k, arg in enumerate(args): value = arg["value"] if isinstance(value, dict) and value.get("__class__") == "Template": if self.export_dir: # all relative path image_path = value['filename'] if not os.path.isfile(os.path.join(self.script_root, image_path)) and value['_filepath']: # copy image used by using statement shutil.copyfile(value['_filepath'], os.path.join(self.script_root, value['filename'])) else: image_path = os.path.abspath(value['_filepath'] or value['filename']) arg["image"] = image_path try: if not value['_filepath'] and not os.path.exists(value['filename']): crop_img = imread(os.path.join(self.script_root, value['filename'])) else: crop_img = imread(value['_filepath'] or value['filename']) except FileNotExistError: # 在某些情况下会报图片不存在的错误(偶现),但不应该影响主流程 if os.path.exists(image_path): arg["resolution"] = get_resolution(imread(image_path)) else: arg["resolution"] = (0, 0) else: arg["resolution"] = get_resolution(crop_img) return code @staticmethod def div_rect(r): """count rect for js use""" xs = [p[0] for p in r] ys = [p[1] for p in r] left = min(xs) top = min(ys) w = max(xs) - left h = max(ys) - top return {'left': left, 'top': top, 'width': w, 'height': h} def _translate_desc(self, step, code): """ 函数描述 """ if step['tag'] != "function": return None name = step['data']['name'] res = step['data'].get('ret') args = {i["key"]: i["value"] for i in code["args"]} desc = { "snapshot": lambda: u"Screenshot description: %s" % args.get("msg"), "touch": lambda: u"Touch %s" % ("target image" if isinstance(args['v'], dict) else "coordinates %s" % args['v']), "swipe": u"Swipe on screen", "wait": u"Wait for target image to appear", "exists": lambda: u"Image %s exists" % ("" if res else "not"), "text": lambda: u"Input text:%s" % args.get('text'), "keyevent": lambda: u"Click [%s] button" % args.get('keyname'), "sleep": lambda: u"Wait for %s seconds" % args.get('secs'), "assert_exists": u"Assert target image exists", "assert_not_exists": u"Assert target image does not exists", "connect_device": lambda : u"Connect device: %s" % args.get("uri"), } # todo: 最好用js里的多语言实现 desc_zh = { "snapshot": lambda: u"截图描述: %s" % args.get("msg"), "touch": lambda: u"点击 %s" % (u"目标图片" if isinstance(args['v'], dict) else u"屏幕坐标 %s" % args['v']), "swipe": u"滑动操作", "wait": u"等待目标图片出现", "exists": lambda: u"图片%s存在" % ("" if res else u"不"), "text": lambda: u"输入文字:%s" % args.get('text'), "keyevent": lambda: u"点击[%s]按键" % args.get('keyname'), "sleep": lambda: u"等待%s秒" % args.get('secs'), "assert_exists": u"断言目标图片存在", "assert_not_exists": u"断言目标图片不存在", "connect_device": lambda : u"连接设备: %s" % args.get("uri"), } if self.lang == "zh": desc = desc_zh ret = desc.get(name) if callable(ret): ret = ret() return ret def _translate_title(self, name, step): title = { "touch": u"Touch", "swipe": u"Swipe", "wait": u"Wait", "exists": u"Exists", "text": u"Text", "keyevent": u"Keyevent", "sleep": u"Sleep", "assert_exists": u"Assert exists", "assert_not_exists": u"Assert not exists", "snapshot": u"Snapshot", "assert_equal": u"Assert equal", "assert_not_equal": u"Assert not equal", "connect_device": u"Connect device", } return title.get(name, name) @staticmethod def _render(template_name, output_file=None, **template_vars): """ 用jinja2渲染html""" env = jinja2.Environment( loader=jinja2.FileSystemLoader(STATIC_DIR), extensions=(), autoescape=True ) env.filters['nl2br'] = nl2br env.filters['datetime'] = timefmt template = env.get_template(template_name) html = template.render(**template_vars) if output_file: with io.open(output_file, 'w', encoding="utf-8") as f: f.write(html) LOGGING.info(output_file) return html def is_pos(self, v): return isinstance(v, (list, tuple)) def copy_tree(self, src, dst, ignore=None): try: shutil.copytree(src, dst, ignore=ignore) except: LOGGING.error(traceback.format_exc()) def _make_export_dir(self): """mkdir & copy /staticfiles/screenshots""" # let dirname = <script name>.log dirname = self.script_name.replace(os.path.splitext(self.script_name)[1], ".log") # mkdir dirpath = os.path.join(self.export_dir, dirname) if os.path.isdir(dirpath): shutil.rmtree(dirpath, ignore_errors=True) # copy script def ignore_export_dir(dirname, filenames): # 忽略当前导出的目录,防止递归导出 if os.path.commonprefix([dirpath, dirname]) == dirpath: return filenames return [] self.copy_tree(self.script_root, dirpath, ignore=ignore_export_dir) # copy log logpath = os.path.join(dirpath, DEFAULT_LOG_DIR) if os.path.normpath(logpath) != os.path.normpath(self.log_root): if os.path.isdir(logpath): shutil.rmtree(logpath, ignore_errors=True) self.copy_tree(self.log_root, logpath, ignore=shutil.ignore_patterns(dirname)) # if self.static_root is not a http server address, copy static files from local directory if not self.static_root.startswith("http"): for subdir in ["css", "fonts", "image", "js"]: self.copy_tree(os.path.join(self.static_root, subdir), os.path.join(dirpath, "static", subdir)) return dirpath, logpath def get_relative_log(self, output_file): """ Try to get the relative path of log.txt :param output_file: output file: log.html :return: ./log.txt or "" """ try: html_dir = os.path.dirname(output_file) if self.export_dir: # When exporting reports, the log directory will be named log/ (DEFAULT_LOG_DIR), # so the relative path of log.txt is log/log.txt return os.path.join(DEFAULT_LOG_DIR, os.path.basename(self.logfile)) return os.path.relpath(os.path.join(self.log_root, self.logfile), html_dir) except: LOGGING.error(traceback.format_exc()) return "" def get_console(self, output_file): html_dir = os.path.dirname(output_file) file = os.path.join(html_dir, 'console.txt') content = "" if os.path.isfile(file): try: content = self.readFile(file) except Exception: try: content = self.readFile(file, "gbk") except Exception: content = traceback.format_exc() + content content = content + "Can not read console.txt. Please check file in:\n" + file return content def readFile(self, filename, code='utf-8'): content = "" with io.open(filename, encoding=code) as f: for line in f.readlines(): content = content + line return content def report_data(self, output_file=None, record_list=None): """ Generate data for the report page :param output_file: The file name or full path of the output file, default HTML_FILE :param record_list: List of screen recording files :return: """ self._load() steps = self._analyse() script_path = os.path.join(self.script_root, self.script_name) info = json.loads(get_script_info(script_path)) info['devices'] = self.devices if record_list: records = [os.path.join(DEFAULT_LOG_DIR, f) if self.export_dir else os.path.abspath(os.path.join(self.log_root, f)) for f in record_list] else: records = [] if not self.static_root.endswith(os.path.sep): self.static_root = self.static_root.replace("\\", "/") self.static_root += "/" if not output_file: output_file = HTML_FILE data = {} data['steps'] = steps data['name'] = self.script_root data['scale'] = self.scale data['test_result'] = self.test_result data['run_end'] = self.run_end data['run_start'] = self.run_start data['static_root'] = self.static_root data['lang'] = self.lang data['records'] = records data['info'] = info data['log'] = self.get_relative_log(output_file) data['console'] = self.get_console(output_file) # 如果带有<>符号,容易被highlight.js认为是特殊语法,有可能导致页面显示异常,尝试替换成不常用的{} info = json.dumps(data).replace("<", "{").replace(">", "}") data['data'] = info return data def report(self, template_name=HTML_TPL, output_file=HTML_FILE, record_list=None): """ Generate the report page, you can add custom data and overload it if needed :param template_name: default is HTML_TPL :param output_file: The file name or full path of the output file, default HTML_FILE :param record_list: List of screen recording files :return: """ if not self.script_name: path, self.script_name = script_dir_name(self.script_root) if self.export_dir: self.script_root, self.log_root = self._make_export_dir() # output_file可传入文件名,或绝对路径 output_file = output_file if output_file and os.path.isabs(output_file) \ else os.path.join(self.script_root, output_file or HTML_FILE) if not self.static_root.startswith("http"): self.static_root = "static/" if not record_list: record_list = [f for f in os.listdir(self.log_root) if f.endswith(".mp4")] data = self.report_data(output_file=output_file, record_list=record_list) return self._render(template_name, output_file, **data)
class LogToHtml(object): '''Convert log to html display ''' def __init__(self, script_root, log_root="", static_root="", export_dir=None, script_name="", logfile=None, lang="en", plugins=None): pass @staticmethod def init_plugin_modules(plugins): pass def _load(self): pass def _analyse(self): ''' 解析log成可渲染的dict ''' pass def _translate_step(self, step): '''translate single step''' pass def _translate_assertion(self, step): pass def _translate_screen(self, step, code): pass def _translate_device(self, step): pass @classmethod def get_thumbnail(cls, path): '''compress screenshot''' pass @classmethod def get_small_name(cls, filename): pass def _translate_info(self, step): pass def _translate_code(self, step): pass @staticmethod def div_rect(r): '''count rect for js use''' pass def _translate_desc(self, step, code): ''' 函数描述 ''' pass def _translate_title(self, name, step): pass @staticmethod def _render(template_name, output_file=None, **template_vars): ''' 用jinja2渲染html''' pass def is_pos(self, v): pass def copy_tree(self, src, dst, ignore=None): pass def _make_export_dir(self): '''mkdir & copy /staticfiles/screenshots''' pass def ignore_export_dir(dirname, filenames): pass def get_relative_log(self, output_file): ''' Try to get the relative path of log.txt :param output_file: output file: log.html :return: ./log.txt or "" ''' pass def get_console(self, output_file): pass def readFile(self, filename, code='utf-8'): pass def report_data(self, output_file=None, record_list=None): ''' Generate data for the report page :param output_file: The file name or full path of the output file, default HTML_FILE :param record_list: List of screen recording files :return: ''' pass def report_data(self, output_file=None, record_list=None): ''' Generate the report page, you can add custom data and overload it if needed :param template_name: default is HTML_TPL :param output_file: The file name or full path of the output file, default HTML_FILE :param record_list: List of screen recording files :return: ''' pass
31
11
18
1
15
2
4
0.12
1
7
2
1
19
12
24
24
480
53
383
120
352
46
301
112
275
16
1
4
95
3,344
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/settings.py
airtest.core.settings.Settings
class Settings(object): DEBUG = False LOG_DIR = None LOG_FILE = "log.txt" RESIZE_METHOD = staticmethod(cocos_min_strategy) # keypoint matching: kaze/brisk/akaze/orb, contrib: sift/surf/brief CVSTRATEGY = ["mstpl", "tpl", "sift", "brisk"] if LooseVersion('3.4.2') < LooseVersion(cv2.__version__) < LooseVersion('4.4.0'): CVSTRATEGY = ["mstpl", "tpl", "brisk"] KEYPOINT_MATCHING_PREDICTION = True THRESHOLD = 0.7 # [0, 1] THRESHOLD_STRICT = None # dedicated parameter for assert_exists OPDELAY = 0.1 FIND_TIMEOUT = 20 FIND_TIMEOUT_TMP = 3 PROJECT_ROOT = os.environ.get("PROJECT_ROOT", "") # for ``using`` other script SNAPSHOT_QUALITY = 10 # 1-100 https://pillow.readthedocs.io/en/5.1.x/handbook/image-file-formats.html#jpeg # Image compression size, e.g. 1200, means that the size of the screenshot does not exceed 1200*1200 IMAGE_MAXSIZE = os.environ.get("IMAGE_MAXSIZE", None) SAVE_IMAGE = True
class Settings(object): pass
1
0
0
0
0
0
0
0.33
1
0
0
0
0
0
0
0
21
1
18
16
17
6
18
16
17
0
1
1
0
3,345
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_api.py
tests.test_api.TestMainOnAndroid
class TestMainOnAndroid(unittest.TestCase): @classmethod def setUpClass(cls): if not isinstance(G.DEVICE, Android): connect_device("Android:///") ST.CVSTRATEGY = ['tpl'] # 'tpl' is enough for these tests cls.dev = G.DEVICE def test_connect(self): old = len(G.DEVICE_LIST) d = connect_device("Android://localhost:5037/?cap_method=JAVACAP") self.assertEqual(len(G.DEVICE_LIST) - old, 1) self.assertIs(d, G.DEVICE) self.assertEqual(d.cap_method, CAP_METHOD.JAVACAP) set_current(0) def test_device(self): d = device() self.assertIs(d, G.DEVICE) def test_set_current(self): set_current(0) self.assertIs(G.DEVICE, G.DEVICE_LIST[0]) with self.assertRaises(IndexError): set_current(len(G.DEVICE_LIST)) def test_shell(self): output = shell("pwd") self.assertIn("/", output) def test_shell_error(self): with self.assertRaises(AdbShellError): output = shell("nimeqi") self.assertIn("nimei: not found", output) def test_install(self): if PKG in self.dev.list_app(): uninstall(PKG) install(APK) self.assertIn(PKG, self.dev.list_app()) def test_uninstall(self): if PKG not in self.dev.list_app(): install(APK) uninstall(PKG) self.assertNotIn(PKG, self.dev.list_app()) def test_start_app(self): if PKG not in self.dev.list_app(): install(APK) start_app(PKG) def test_clear_app(self): if PKG not in self.dev.list_app(): install(APK) clear_app(PKG) def test_stop_app(self): if PKG not in self.dev.list_app(): install(APK) start_app(PKG) stop_app(PKG) def test_snapshot(self): filename = DIR("./screen.png") if os.path.exists(filename): os.remove(filename) snapshot(filename=filename) self.assertTrue(os.path.exists(filename)) def test_wake(self): wake() def test_home(self): home() def test_touch_pos(self): touch((1, 1)) def test_swipe(self): swipe((0, 0), (10, 10)) swipe((0, 0), (10, 10), fingers=1) swipe((0, 0), (10, 10), fingers=2) with self.assertRaises(Exception): swipe((0, 0), (10, 10), fingers=3) def test_pinch(self): pinch() def test_keyevent(self): keyevent("HOME") def test_text(self): text("input") def test_touch_tpl(self): self._start_apk_main_scene() touch(TPL) self._start_apk_main_scene() with self.assertRaises(TargetNotFoundError): touch(TPL2) def test_wait(self): self._start_apk_main_scene() pos = wait(TPL) self.assertIsInstance(pos, (tuple, list)) with self.assertRaises(TargetNotFoundError): wait(TPL2, timeout=5) def test_exists(self): self._start_apk_main_scene() pos = exists(TPL) self.assertIsInstance(pos, (tuple, list)) self.assertFalse(exists(TPL2)) def _start_apk_main_scene(self): if PKG not in self.dev.list_app(): install(APK) stop_app(PKG) start_app(PKG) def test_log(self): log("hello world") log({"key": "value"}, timestamp=time.time(), desc="log dict") try: 1 / 0 except Exception as e: log(e)
class TestMainOnAndroid(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_connect(self): pass def test_device(self): pass def test_set_current(self): pass def test_shell(self): pass def test_shell_error(self): pass def test_install(self): pass def test_uninstall(self): pass def test_start_app(self): pass def test_clear_app(self): pass def test_stop_app(self): pass def test_snapshot(self): pass def test_wake(self): pass def test_home(self): pass def test_touch_pos(self): pass def test_swipe(self): pass def test_pinch(self): pass def test_keyevent(self): pass def test_text(self): pass def test_touch_tpl(self): pass def test_wait(self): pass def test_exists(self): pass def _start_apk_main_scene(self): pass def test_log(self): pass
26
0
4
0
4
0
1
0.01
1
10
6
0
23
0
24
96
132
27
105
35
79
1
104
33
79
2
2
1
33
3,346
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_android_recorder.py
tests.test_android_recorder.TestAndroidRecorder
class TestAndroidRecorder(unittest.TestCase): """Test Android screen recording function""" @classmethod def setUpClass(cls): cls.android = Android() cls.filepath = "screen.mp4" @classmethod def tearDownClass(cls): try_remove('screen.mp4') def tearDown(self): try_remove("screen.mp4") def test_recording(self): if self.android.sdk_version >= 19: self.android.start_recording(mode="yosemite", max_time=30, bit_rate=500000) time.sleep(10) self.android.stop_recording(self.filepath) self.assertTrue(os.path.exists(self.filepath)) time.sleep(2) # Record the screen with the lower quality os.remove(self.filepath) self.android.start_recording(mode="yosemite", bit_rate_level=1) time.sleep(10) self.android.stop_recording(self.filepath) self.assertTrue(os.path.exists(self.filepath)) os.remove(self.filepath) time.sleep(2) self.android.start_recording(mode="yosemite", bit_rate_level=0.5) time.sleep(10) self.android.stop_recording(self.filepath) self.assertTrue(os.path.exists(self.filepath)) def test_recording_two_recorders(self): """测试用另外一个Recorder结束录制""" self.android.start_recording(max_time=30, mode="yosemite") time.sleep(6) recorder = Recorder(self.android.adb) recorder.stop_recording(self.filepath) self.assertTrue(os.path.exists(self.filepath)) def test_start_recording_error(self): """测试多次调用start_recording""" if self.android.sdk_version >= 19: with self.assertRaises(AirtestError): self.android.start_recording(max_time=30, mode="yosemite") time.sleep(6) self.android.start_recording(max_time=30, mode="yosemite") def test_stop_recording_error(self): with self.assertRaises(AirtestError): self.android.stop_recording() def test_interrupt_recording(self): """测试中断录屏但不导出文件""" self.android.start_recording(max_time=30, mode="yosemite") time.sleep(3) self.android.stop_recording(self.filepath, is_interrupted=True) self.assertFalse(os.path.exists(self.filepath)) def test_pull_last_recording_file(self): self.android.start_recording(max_time=30, mode="yosemite") time.sleep(3) self.android.stop_recording(is_interrupted=True) self.android.recorder.pull_last_recording_file(self.filepath) self.assertTrue(os.path.exists(self.filepath))
class TestAndroidRecorder(unittest.TestCase): '''Test Android screen recording function''' @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def tearDownClass(cls): pass def test_recording(self): pass def test_recording_two_recorders(self): '''测试用另外一个Recorder结束录制''' pass def test_start_recording_error(self): '''测试多次调用start_recording''' pass def test_stop_recording_error(self): pass def test_interrupt_recording(self): '''测试中断录屏但不导出文件''' pass def test_pull_last_recording_file(self): pass
12
4
6
0
6
0
1
0.09
1
3
3
0
7
1
9
81
67
8
54
14
42
5
52
11
42
2
2
2
11
3,347
AirtestProject/Airtest
AirtestProject_Airtest/playground/ui.py
ui.AutomatorWrapper
class AutomatorWrapper(object): def __init__(self, obj, parent=None, assertion=None): super(AutomatorWrapper, self).__init__() self.obj = obj self.parent = parent # prev layer obj self.selectors = None self.select_action = None self.assertion = assertion def __getattr__(self, action): global log, action_stack assertion = None if action.startswith('assert_not_'): assertion = 'assert_not_' action = action[len(assertion):] elif action.startswith('assert_'): assertion = 'assert_' action = action[len(assertion):] important = True is_key_action = False if action in PRIMARY_ACTION: is_key_action = True if action in QUERY_ACTION and not assertion: important = False if important: action_stack.append(action) if is_key_action: log.append({'primary-action': action}) else: log.append({'action': action}) attr = getattr(self.obj, action) if callable(attr) or assertion: return self.__class__(attr, self, assertion=assertion) else: return attr def __call__(self, *args, **kwargs): global log, action_stack calling = None # handle assertion expr assert_value = False if self.assertion == 'assert_not_' else True if self.assertion: action = action_stack[-1] assert_result = self.obj == assert_value prev_selector_obj = self._get_selector_obj() # 必须预先判断所选对象是否存在,不存在的对象调用info属性时会抛出uiautomator.UiObjectNotFoundException # 因为即使是assert_not_checked时,也是可以获取对象info的 if prev_selector_obj.obj.exists: uiobj = prev_selector_obj.obj.info else: uiobj = None assert_action = self.assertion + action genlog('assert', [assert_action, prev_selector_obj.selectors, assert_result] + list(args), uiobj) if not assert_result: try: raise AutomatorAssertionFail('assert failed of {}, require {}, got {}'.format(assert_action, assert_value, self.obj)) except AutomatorAssertionFail: log_error('assert', traceback.format_exc(), assert_action, prev_selector_obj.selectors, assert_result, *args, **kwargs) raise return None # handle selector expr if args or kwargs: if all([k in SELECTOR_ARGS for k in kwargs]): # get this select action name if len(action_stack) >= 1: action = action_stack[-1] else: action = 'global' # relative selector prev_selector_obj = self._get_selector_obj() if prev_selector_obj: uiobj = try_getattr(prev_selector_obj.obj, 'info', prev_selector_obj.select_action, prev_selector_obj.selectors) genlog('select', [prev_selector_obj.select_action, prev_selector_obj.selectors], uiobj) calling = try_call(self.obj, action, *args, **kwargs) ret = self.__class__(calling, self) ret.selectors = (args, kwargs) if args else kwargs ret.select_action = action return ret # 其他操作的log记录 action, params = None, None if args or kwargs: last_log = list(args) or kwargs.values() else: last_log = [] if len(action_stack) >= 3 and action_stack[-3] in TERTIARY_ACTION: taction = TERTIARY_ACTION[action_stack[-3]] if action_stack[-2] in taction: saction = taction[action_stack[-2]] if action_stack[-1] in saction: action = action_stack[-3] params = action_stack[-2:] + last_log if len(action_stack) >= 2 and action_stack[-2] in SECONDARY_ACTIONS: secondary_action = SECONDARY_ACTIONS[action_stack[-2]] if action_stack[-1] in secondary_action: action = action_stack[-2] params = action_stack[-1:] + last_log if len(action_stack) >= 1 and action_stack[-1] in PRIMARY_ACTION: action = action_stack[-1] params = last_log if action: # select操作log记录 selector_obj = self._get_selector_obj() uiobj = None if selector_obj: uiobj = try_getattr(selector_obj.obj, 'info', selector_obj.select_action, selector_obj.selectors) genlog('select', [selector_obj.select_action, selector_obj.selectors], uiobj) genlog(action, params, uiobj) if not calling: calling = try_call(self.obj, 'action', *args, **kwargs) return self.__class__(calling, self) def __len__(self): return len(self.obj) def __nonzero__(self): """ python 2 only, for python 3, please override __bool__ """ return bool(self.obj) def __getitem__(self, item): return self.__class__(self.obj[item], self) def __iter__(self): objs, length = self, len(self) class Iter(object): def __init__(self): self.index = -1 def next(self): self.index += 1 if self.index < length: return objs[self.index] else: raise StopIteration() __next__ = next return Iter() def _get_selector_obj(self): # 下面的is not None的判断方法有点特殊 # 因为该类实现了bool隐式转换接口,如果不这样判断的话,在and表达式返回时,还会自动bool隐式转换一次 # 导致条件判断非预期 ret = None if self.selectors: ret = self elif (self.parent and self.parent.selectors) is not None: ret = self.parent elif (self.parent and self.parent.parent and self.parent.parent.selectors) is not None: ret = self.parent.parent elif (self.parent and self.parent.parent and self.parent.parent.parent and self.parent.parent.parent.selectors) is not None: ret = self.parent.parent.parent return ret def end(self): time.sleep(1) genlog('end', [], None)
class AutomatorWrapper(object): def __init__(self, obj, parent=None, assertion=None): pass def __getattr__(self, action): pass def __call__(self, *args, **kwargs): pass def __len__(self): pass def __nonzero__(self): ''' python 2 only, for python 3, please override __bool__ ''' pass def __getitem__(self, item): pass def __iter__(self): pass class Iter(object): def __init__(self, obj, parent=None, assertion=None): pass def next(self): pass def _get_selector_obj(self): pass def end(self): pass
13
1
15
1
13
1
4
0.11
1
5
2
0
9
5
9
9
169
23
133
42
118
14
123
42
108
21
1
3
43
3,348
AirtestProject/Airtest
AirtestProject_Airtest/playground/win_ide.py
win_ide.WindowsInIDE
class WindowsInIDE(Windows): """Windows Device in Airtest-IDE""" def __init__(self, handle=None, dpifactor=1, **kwargs): if isinstance(handle, str) and handle.isdigit(): handle = int(handle) super(WindowsInIDE, self).__init__(handle, dpifactor=dpifactor, **kwargs) self.handle = handle def connect(self, **kwargs): """ Connect to window and set it foreground Args: **kwargs: optional arguments Returns: None """ self.app = self._app.connect(**kwargs) try: self._top_window = self.app.top_window().wrapper_object() if kwargs.get("foreground", True) in (True, "True", "true"): self.set_foreground() except RuntimeError: self._top_window = None def get_rect(self): """ Get rectangle of app or desktop resolution Returns: RECT(left, top, right, bottom) """ if self.handle: left, top, right, bottom = win32gui.GetWindowRect(self.handle) return RECT(left, top, right, bottom) else: desktop = win32gui.GetDesktopWindow() left, top, right, bottom = win32gui.GetWindowRect(desktop) return RECT(left, top, right, bottom) def snapshot(self, filename="tmp.png"): """ Take a screenshot and save it to `tmp.png` filename by default Args: filename: name of file where to store the screenshot Returns: display the screenshot """ if not filename: filename = "tmp.png" if self.handle: try: screenshot(filename, self.handle) except win32gui.error: self.handle = None screenshot(filename) else: screenshot(filename) img = aircv.imread(filename) os.remove(filename) return img
class WindowsInIDE(Windows): '''Windows Device in Airtest-IDE''' def __init__(self, handle=None, dpifactor=1, **kwargs): pass def connect(self, **kwargs): ''' Connect to window and set it foreground Args: **kwargs: optional arguments Returns: None ''' pass def get_rect(self): ''' Get rectangle of app or desktop resolution Returns: RECT(left, top, right, bottom) ''' pass def snapshot(self, filename="tmp.png"): ''' Take a screenshot and save it to `tmp.png` filename by default Args: filename: name of file where to store the screenshot Returns: display the screenshot ''' pass
5
4
16
3
9
5
3
0.56
1
4
0
0
4
3
4
66
70
14
36
11
31
20
34
11
29
4
3
2
11
3,349
AirtestProject/Airtest
AirtestProject_Airtest/playground/xy.py
xy.CustomAirtestCase
class CustomAirtestCase(AirtestCase): def setUp(self): print("custom setup") # add var/function/class/.. to globals # self.scope["hunter"] = "i am hunter" # self.scope["add"] = lambda x: x+1 # exec setup script # self.exec_other_script("setup.owl") super(CustomAirtestCase, self).setUp() def tearDown(self): print("custom tearDown") # exec teardown script # self.exec_other_script("teardown.owl") super(CustomAirtestCase, self).setUp()
class CustomAirtestCase(AirtestCase): def setUp(self): pass def tearDown(self): pass
3
0
7
1
3
4
1
1
1
1
0
0
2
0
2
79
17
3
7
3
4
7
7
3
4
1
3
0
2
3,350
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.TargetNotFoundError
class TargetNotFoundError(AirtestError): """ This is TargetNotFoundError BaseError When something is not found """ pass
class TargetNotFoundError(AirtestError): ''' This is TargetNotFoundError BaseError When something is not found ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
12
6
0
2
1
1
4
2
1
1
0
5
0
0
3,351
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/helper.py
airtest.core.helper.DeviceMetaProperty
class DeviceMetaProperty(type): @property def DEVICE(cls): if G._DEVICE is None: raise NoDeviceError("No devices added.") return G._DEVICE @DEVICE.setter def DEVICE(cls, dev): cls._DEVICE = dev
class DeviceMetaProperty(type): @property def DEVICE(cls): pass @DEVICE.setter def DEVICE(cls): pass
5
0
3
0
3
0
2
0
1
2
2
1
2
0
2
15
11
2
9
5
4
0
7
3
4
2
2
1
3
3,352
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_apkparser.py
tests.test_apkparser.TestAPK
class TestAPK(unittest.TestCase): def test_version(self): v = apkparser(APK).androidversion_code self.assertEqual(v, "1") def test_package(self): p = apkparser(APK).get_package() self.assertEqual(p, PKG)
class TestAPK(unittest.TestCase): def test_version(self): pass def test_package(self): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
0
2
74
9
2
7
5
4
0
7
5
4
1
2
0
2
3,353
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/mjpeg_cap.py
airtest.core.ios.mjpeg_cap.SocketBuffer
class SocketBuffer(SafeSocket): def __init__(self, sock: socket.socket): super(SocketBuffer, self).__init__(sock) def _drain(self): _data = self.sock.recv(1024) if _data is None or _data == b"": raise IOError("socket closed") self.buf += _data return len(_data) def read_until(self, delimeter: bytes) -> bytes: """ return without delimeter """ while True: index = self.buf.find(delimeter) if index != -1: _return = self.buf[:index] self.buf = self.buf[index + len(delimeter):] return _return self._drain() def read_bytes(self, length: int) -> bytes: while length > len(self.buf): self._drain() _return, self.buf = self.buf[:length], self.buf[length:] return _return def write(self, data: bytes): return self.sock.sendall(data)
class SocketBuffer(SafeSocket): def __init__(self, sock: socket.socket): pass def _drain(self): pass def read_until(self, delimeter: bytes) -> bytes: ''' return without delimeter ''' pass def read_bytes(self, length: int) -> bytes: pass def write(self, data: bytes): pass
6
1
5
0
5
0
2
0.04
1
4
0
0
5
1
5
14
30
5
24
11
18
1
24
11
18
3
2
2
9
3,354
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/win/win.py
airtest.core.win.win.Windows
class Windows(Device): """Windows client.""" def __init__(self, handle=None, dpifactor=1, **kwargs): super(Windows, self).__init__() self.app = None self.handle = int(handle) if handle else None # windows high dpi scale factor, no exact way to auto detect this value for a window # reference: https://msdn.microsoft.com/en-us/library/windows/desktop/mt843498(v=vs.85).aspx self._dpifactor = float(dpifactor) self._app = Application() self._top_window = None self._focus_rect = (0, 0, 0, 0) self.mouse = mouse self.keyboard = keyboard self._init_connect(handle, kwargs) self.screen = mss.mss() self.monitor = self.screen.monitors[0] # 双屏的时候,self.monitor为整个双屏 self.main_monitor = self.screen.monitors[1] # 双屏的时候,self.main_monitor为主屏 @property def uuid(self): return self.handle def _init_connect(self, handle, kwargs): if handle: self.connect(handle=handle, **kwargs) elif kwargs: self.connect(**kwargs) def connect(self, handle=None, **kwargs): """ Connect to window and set it foreground Args: **kwargs: optional arguments Returns: None """ if handle: handle = int(handle) self.app = self._app.connect(handle=handle) self._top_window = self.app.window(handle=handle).wrapper_object() else: for k in ["process", "timeout"]: if k in kwargs: kwargs[k] = int(kwargs[k]) self.app = self._app.connect(**kwargs) self._top_window = self.app.top_window().wrapper_object() if kwargs.get("foreground", True) in (True, "True", "true"): try: self.set_foreground() except pywintypes.error as e: # pywintypes.error: (0, 'SetForegroundWindow', 'No error message is available') # If you are not running with administrator privileges, it may fail, but this error can be ignored. pass def shell(self, cmd): """ Run shell command in subprocess Args: cmd: command to be run Raises: subprocess.CalledProcessError: when command returns non-zero exit status Returns: command output as a byte string """ return subprocess.check_output(cmd, shell=True) def snapshot_old(self, filename=None, quality=10, max_size=None): """ Take a screenshot and save it in ST.LOG_DIR folder Args: filename: name of the file to give to the screenshot, {time}.jpg by default quality: The image quality, integer in range [1, 99] max_size: the maximum size of the picture, e.g 1200 Returns: display the screenshot """ if self.handle: screen = screenshot(filename, self.handle) else: screen = screenshot(filename) if self.app: rect = self.get_rect() rect = self._fix_image_rect(rect) screen = aircv.crop_image(screen, [rect.left, rect.top, rect.right, rect.bottom]) if not screen.any(): if self.app: rect = self.get_rect() rect = self._fix_image_rect(rect) screen = aircv.crop_image(screenshot(filename), [rect.left, rect.top, rect.right, rect.bottom]) if self._focus_rect != (0, 0, 0, 0): height, width = screen.shape[:2] rect = (self._focus_rect[0], self._focus_rect[1], width + self._focus_rect[2], height + self._focus_rect[3]) screen = aircv.crop_image(screen, rect) if filename: aircv.imwrite(filename, screen, quality, max_size=max_size) return screen def snapshot(self, filename=None, quality=10, max_size=None): """ Take a screenshot and save it in ST.LOG_DIR folder Args: filename: name of the file to give to the screenshot, {time}.jpg by default quality: The image quality, integer in range [1, 99] max_size: the maximum size of the picture, e.g 1200 Returns: display the screenshot """ if self.app: rect = self.get_rect() rect = self._fix_image_rect(rect) monitor = {"top": rect.top, "left": rect.left, "width": rect.right - rect.left - abs(self.monitor["left"]), "height": rect.bottom - rect.top, "monitor": 1} else: monitor = self.screen.monitors[0] try: with mss.mss() as sct: sct_img = sct.grab(monitor) screen = numpy.array(sct_img, dtype=numpy.uint8)[..., :3] if filename: aircv.imwrite(filename, screen, quality, max_size=max_size) return screen except: # if mss.exception.ScreenShotError: gdi32.GetDIBits() failed. return self.snapshot_old(filename, quality, max_size) def _fix_image_rect(self, rect): """Fix rect in image.""" # 将rect 转换为左上角为(0,0), 与图片坐标对齐,另外left不用重新计算 rect.right = rect.right - self.monitor["left"] rect.top = rect.top - self.monitor["top"] rect.bottom = rect.bottom - self.monitor["top"] return rect def keyevent(self, keyname, **kwargs): """ Perform a key event References: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html Args: keyname: key event **kwargs: optional arguments Returns: None """ self.keyboard.SendKeys(keyname) def text(self, text, **kwargs): """ Input text Args: text: text to input **kwargs: optional arguments Returns: None """ self.keyevent(text) def _fix_op_pos(self, pos): """Fix operation position.""" # 如果是全屏的话,就进行双屏修正,否则就正常即可 if not self.handle: pos = list(pos) pos[0] = pos[0] + self.monitor["left"] pos[1] = pos[1] + self.monitor["top"] return pos def key_press(self, key): """Simulates a key press event. Sends a scancode to the computer to report which key has been pressed. Some games use DirectInput devices, and respond only to scancodes, not virtual key codes. You can simulate DirectInput key presses using this method, instead of the keyevent() method, which uses virtual key codes. :param key: A string indicating which key to be pressed. Available key options are: {'ESCAPE', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 'BACKSPACE', 'TAB', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', 'ENTER', 'LCTRL', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', "'", '`', 'LSHIFT', 'BACKSLASH', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'RSHIFT', '*', 'LALT', 'SPACE', 'CAPS_LOCK', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'NUM_LOCK', 'SCROLL_LOCK', 'NUMPAD_7', 'NUMPAD_8', 'NUMPAD_9', 'NUMPAD_-', 'NUMPAD_4', 'NUMPAD_5', 'NUMPAD_6', 'NUMPAD_+', 'NUMPAD_1', 'NUMPAD_2', 'NUMPAD_3', 'NUMPAD_0', 'NUMPAD_.', 'F11', 'F12', 'PRINT_SCREEN', 'PAUSE', 'NUMPAD_ENTER', 'RCTRL', 'NUMPAD_/', 'RALT', 'HOME', 'UP', 'PAGE_UP', 'LEFT', 'RIGHT', 'END', 'DOWN', 'PAGE_DOWN', 'INSERT', 'DELETE', 'LWINDOWS', 'RWINDOWS', 'MENU'}. """ key_press(key) def key_release(self, key): """Simulates a key release event. Sends a scancode to the computer to report which key has been released. Some games use DirectInput devices, and respond only to scancodes, not virtual key codes. You can simulate DirectInput key releases using this method. A call to the key_release() method usually follows a call to the key_press() method of the same key. :param key: A string indicating which key to be released. """ key_release(key) def touch(self, pos, **kwargs): """ Perform mouse click action References: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.mouse.html Args: pos: coordinates where to click **kwargs: optional arguments Examples: >>> from airtest.core.api import connect_device >>> dev = connect_device("Windows:///") >>> dev.touch((100, 100)) # absolute coordinates >>> dev.touch((0.5, 0.5)) # relative coordinates Returns: None """ duration = kwargs.get("duration", 0.01) right_click = kwargs.get("right_click", False) button = "right" if right_click else "left" steps = kwargs.get("steps", 1) offset = kwargs.get("offset", 0) start = self._action_pos(win32api.GetCursorPos()) ori_end = get_absolute_coordinate(pos, self) end = self._action_pos(ori_end) start_x, start_y = self._fix_op_pos(start) end_x, end_y = self._fix_op_pos(end) interval = float(duration) / steps time.sleep(interval) for i in range(1, steps): x = int(start_x + (end_x - start_x) * i / steps) y = int(start_y + (end_y - start_y) * i / steps) self.mouse.move(coords=(x, y)) time.sleep(interval) self.mouse.move(coords=(end_x, end_y)) for i in range(1, offset + 1): self.mouse.move(coords=(end_x + i, end_y + i)) time.sleep(0.01) for i in range(offset): self.mouse.move(coords=(end_x + offset - i, end_y + offset - i)) time.sleep(0.01) self.mouse.press(button=button, coords=(end_x, end_y)) time.sleep(duration) self.mouse.release(button=button, coords=(end_x, end_y)) return ori_end def double_click(self, pos): ori_pos = get_absolute_coordinate(pos, self) coords = self._fix_op_pos(self._action_pos(ori_pos)) self.mouse.double_click(coords=coords) return ori_pos def swipe(self, p1, p2, duration=0.8, steps=5, button="left"): """ Perform swipe (mouse press and mouse release) Args: p1: start point p2: end point duration: time interval to perform the swipe action steps: size of the swipe step button: mouse button to press, 'left', 'right' or 'middle', default is 'left' Examples: >>> from airtest.core.api import connect_device >>> dev = connect_device("Windows:///") >>> dev.swipe((100, 100), (200, 200), duration=0.5) >>> dev.swipe((0.1, 0.1), (0.2, 0.2), duration=0.5) Returns: None """ # 设置坐标时相对于整个屏幕的坐标: ori_from = get_absolute_coordinate(p1, self) ori_to = get_absolute_coordinate(p2, self) from_x, from_y = self._fix_op_pos(self._action_pos(ori_from)) to_x, to_y = self._fix_op_pos(self._action_pos(ori_to)) interval = float(duration) / (steps + 1) self.mouse.press(coords=(from_x, from_y), button=button) time.sleep(interval) for i in range(1, steps): self.mouse.move(coords=( int(from_x + (to_x - from_x) * i / steps), int(from_y + (to_y - from_y) * i / steps), )) time.sleep(interval) for i in range(10): self.mouse.move(coords=(to_x, to_y)) time.sleep(interval) self.mouse.release(coords=(to_x, to_y), button=button) return ori_from, ori_to def mouse_move(self, pos): """Simulates a `mousemove` event. Known bug: Due to a bug in the pywinauto module, users might experience \ off-by-one errors when it comes to the exact coordinates of \ the position on screen. :param pos: A tuple (x, y), where x and y are x and y coordinates of the screen to move the mouse to, respectively. """ if not isinstance(pos, tuple) or len(pos) != 2: # pos is not a 2-tuple raise ValueError('invalid literal for mouse_move: {}'.format(pos)) try: self.mouse.move(coords=self._action_pos(pos)) except ValueError: # in case where x, y are not numbers raise ValueError('invalid literal for mouse_move: {}'.format(pos)) def mouse_down(self, button='left'): """Simulates a `mousedown` event. :param button: A string indicating which mouse button to be pressed. Available mouse button options are: {'left', 'middle', 'right'}. """ buttons = {'left', 'middle', 'right'} if not isinstance(button, str) or button not in buttons: raise ValueError('invalid literal for mouse_down(): {}'.format(button)) else: coords = self._action_pos(win32api.GetCursorPos()) self.mouse.press(button=button, coords=coords) def mouse_up(self, button='left'): """Simulates a `mouseup` event. A call to the mouse_up() method usually follows a call to the mouse_down() method of the same mouse button. :param button: A string indicating which mouse button to be released. """ buttons = {'left', 'middle', 'right'} if not isinstance(button, str) or button not in buttons: raise ValueError('invalid literal for mouse_up(): {}'.format(button)) else: coords = self._action_pos(win32api.GetCursorPos()) self.mouse.release(button=button, coords=coords) def start_app(self, path, *args, **kwargs): """ Start the application Args: path: full path to the application kwargs: reference: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.application.html#pywinauto.application.Application.start Returns: None """ self.app = self._app.start(path, **kwargs) def stop_app(self, pid): """ Stop the application Args: pid: process ID of the application to be stopped Returns: None """ self._app.connect(process=pid).kill() @require_app def set_foreground(self): """ Bring the window foreground Returns: None """ self._top_window.set_focus() set_focus = set_foreground def get_rect(self): """ Get rectangle Returns: win32structures.RECT """ if self.app and self._top_window: return self._top_window.rectangle() else: return RECT(right=win32api.GetSystemMetrics(0), bottom=win32api.GetSystemMetrics(1)) @require_app def get_title(self): """ Get the window title Returns: window title """ return self._top_window.texts() @require_app def get_pos(self): """ Get the window position coordinates Returns: coordinates of topleft corner of the window (left, top) """ rect = self.get_rect() return (rect.left, rect.top) @require_app def move(self, pos): """ Move window to given coordinates Args: pos: coordinates (x, y) where to move the window Returns: None """ self._top_window.MoveWindow(x=pos[0], y=pos[1]) @require_app def kill(self): """ Kill the application Returns: None """ self.app.kill() def set_clipboard(self, text): """ Set clipboard content Args: text: text to be set to clipboard Examples: >>> from airtest.core.api import connect_device >>> dev = connect_device("Windows:///") >>> dev.set_clipboard("hello world") >>> print(dev.get_clipboard()) 'hello world' >>> dev.paste() # paste the clipboard content Returns: None """ try: win32clipboard.OpenClipboard() except pywintypes.error as e: # pywintypes.error: (5, 'OpenClipboard', '拒绝访问。') # sometimes clipboard is locked by other process, retry after 0.1s time.sleep(0.1) win32clipboard.OpenClipboard() try: win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, text) finally: win32clipboard.CloseClipboard() def get_clipboard(self): """ Get clipboard content Returns: clipboard content """ try: win32clipboard.OpenClipboard() return win32clipboard.GetClipboardData() finally: win32clipboard.CloseClipboard() def paste(self): """ Perform paste action Returns: None """ self.keyevent("^v") def _action_pos(self, pos): if self.app: pos = self._windowpos_to_screenpos(pos) pos = (int(pos[0]), int(pos[1])) return pos # @property # def handle(self): # return self._top_window.handle @property def focus_rect(self): return self._focus_rect @focus_rect.setter def focus_rect(self, value): # set focus rect to get rid of window border assert len(value) == 4, "focus rect must be in [left, top, right, bottom]" self._focus_rect = value def get_current_resolution(self): rect = self.get_rect() w = (rect.right + self._focus_rect[2]) - (rect.left + self._focus_rect[0]) h = (rect.bottom + self._focus_rect[3]) - (rect.top + self._focus_rect[1]) return w, h def _windowpos_to_screenpos(self, pos): """ Convert given position relative to window topleft corner to screen coordinates Args: pos: coordinates (x, y) Returns: converted position coordinates """ rect = self.get_rect() pos = (int((pos[0] + rect.left + self._focus_rect[0]) * self._dpifactor), int((pos[1] + rect.top + self._focus_rect[1]) * self._dpifactor)) return pos def get_ip_address(self): """ Return default external ip address of the windows os. Returns: :py:obj:`str`: ip address """ ifaces = psutil.net_if_addrs() # 常见的虚拟网卡名称关键词 virtual_iface_keywords = ['vEthernet', 'VirtualBox', 'VMware', 'Hyper-V', 'Wireless', 'VPN', 'Loopback'] for interface_name, iface_addresses in ifaces.items(): if any(keyword in interface_name for keyword in virtual_iface_keywords): continue for iface_address in iface_addresses: # 检查IPV4地址 if iface_address.family == socket.AF_INET: # 检查是否为自动获取的APIPA地址 if not iface_address.address.startswith('169.254'): # 返回第一个非APIPA的IPV4地址 return iface_address.address return None def start_recording(self, max_time=1800, output=None, fps=10, snapshot_sleep=0.001, orientation=0, max_size=None, *args, **kwargs): """ Start recording the device display Args: max_time: maximum screen recording time, default is 1800 output: ouput file path mode: the backend write video, choose in ["ffmpeg"] ffmpeg: ffmpeg-python backend, higher compression rate. fps: frames per second will record snapshot_sleep: sleep time for each snapshot. orientation: 1: portrait, 2: landscape, 0: rotation. max_size: max size of the video frame, e.g.800, default is None. Smaller sizes lead to lower system load. Returns: save_path: path of video file Examples: Record 30 seconds of video and export to the current directory test.mp4: >>> from airtest.core.api import connect_device, sleep >>> dev = connect_device("Windows:///") >>> save_path = dev.start_recording(output="test.mp4") >>> sleep(30) >>> dev.stop_recording() >>> print(save_path) You can specify max_size to limit the video's maximum width/length. Smaller video sizes result in lower CPU load. >>> dev.start_recording(output="test.mp4", max_size=800) Note: 1 Don't resize the app window duraing recording, the recording region will be limited by first frame. 2 If recording still working after app crash, it will continuing write last frame before the crash. """ if fps > 10 or fps < 1: LOGGING.warning("fps should be between 1 and 10, becuase of the recording effiency") if fps > 10: fps = 10 if fps < 1: fps = 1 if hasattr(self, 'recorder'): if self.recorder.is_running(): LOGGING.warning("recording is already running, please don't call again") return None logdir = "./" if not ST.LOG_DIR is None: logdir = ST.LOG_DIR if output is None: save_path = os.path.join(logdir, "screen_%s.mp4" % (time.strftime("%Y%m%d%H%M%S", time.localtime()))) else: if os.path.isabs(output): save_path = output else: save_path = os.path.join(logdir, output) max_size = get_max_size(max_size) def get_frame(): try: frame = self.snapshot() except numpy.core._exceptions._ArrayMemoryError: self.stop_recording() raise Exception("memory error!!!!") if max_size is not None: frame = resize_by_max(frame, max_size) return frame self.recorder = ScreenRecorder( save_path, get_frame, fps=fps, snapshot_sleep=snapshot_sleep, orientation=orientation) self.recorder.stop_time = max_time self.recorder.start() LOGGING.info("start recording screen to {}, don't close or resize the app window".format(save_path)) return save_path def stop_recording(self): """ Stop recording the device display. Recoding file will be kept in the device. """ LOGGING.info("stopping recording") self.recorder.stop() return None
class Windows(Device): '''Windows client.''' def __init__(self, handle=None, dpifactor=1, **kwargs): pass @property def uuid(self): pass def _init_connect(self, handle, kwargs): pass def connect(self, handle=None, **kwargs): ''' Connect to window and set it foreground Args: **kwargs: optional arguments Returns: None ''' pass def shell(self, cmd): ''' Run shell command in subprocess Args: cmd: command to be run Raises: subprocess.CalledProcessError: when command returns non-zero exit status Returns: command output as a byte string ''' pass def snapshot_old(self, filename=None, quality=10, max_size=None): ''' Take a screenshot and save it in ST.LOG_DIR folder Args: filename: name of the file to give to the screenshot, {time}.jpg by default quality: The image quality, integer in range [1, 99] max_size: the maximum size of the picture, e.g 1200 Returns: display the screenshot ''' pass def snapshot_old(self, filename=None, quality=10, max_size=None): ''' Take a screenshot and save it in ST.LOG_DIR folder Args: filename: name of the file to give to the screenshot, {time}.jpg by default quality: The image quality, integer in range [1, 99] max_size: the maximum size of the picture, e.g 1200 Returns: display the screenshot ''' pass def _fix_image_rect(self, rect): '''Fix rect in image.''' pass def keyevent(self, keyname, **kwargs): ''' Perform a key event References: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html Args: keyname: key event **kwargs: optional arguments Returns: None ''' pass def text(self, text, **kwargs): ''' Input text Args: text: text to input **kwargs: optional arguments Returns: None ''' pass def _fix_op_pos(self, pos): '''Fix operation position.''' pass def key_press(self, key): '''Simulates a key press event. Sends a scancode to the computer to report which key has been pressed. Some games use DirectInput devices, and respond only to scancodes, not virtual key codes. You can simulate DirectInput key presses using this method, instead of the keyevent() method, which uses virtual key codes. :param key: A string indicating which key to be pressed. Available key options are: {'ESCAPE', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 'BACKSPACE', 'TAB', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', 'ENTER', 'LCTRL', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', "'", '`', 'LSHIFT', 'BACKSLASH', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'RSHIFT', '*', 'LALT', 'SPACE', 'CAPS_LOCK', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'NUM_LOCK', 'SCROLL_LOCK', 'NUMPAD_7', 'NUMPAD_8', 'NUMPAD_9', 'NUMPAD_-', 'NUMPAD_4', 'NUMPAD_5', 'NUMPAD_6', 'NUMPAD_+', 'NUMPAD_1', 'NUMPAD_2', 'NUMPAD_3', 'NUMPAD_0', 'NUMPAD_.', 'F11', 'F12', 'PRINT_SCREEN', 'PAUSE', 'NUMPAD_ENTER', 'RCTRL', 'NUMPAD_/', 'RALT', 'HOME', 'UP', 'PAGE_UP', 'LEFT', 'RIGHT', 'END', 'DOWN', 'PAGE_DOWN', 'INSERT', 'DELETE', 'LWINDOWS', 'RWINDOWS', 'MENU'}. ''' pass def key_release(self, key): '''Simulates a key release event. Sends a scancode to the computer to report which key has been released. Some games use DirectInput devices, and respond only to scancodes, not virtual key codes. You can simulate DirectInput key releases using this method. A call to the key_release() method usually follows a call to the key_press() method of the same key. :param key: A string indicating which key to be released. ''' pass def touch(self, pos, **kwargs): ''' Perform mouse click action References: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.mouse.html Args: pos: coordinates where to click **kwargs: optional arguments Examples: >>> from airtest.core.api import connect_device >>> dev = connect_device("Windows:///") >>> dev.touch((100, 100)) # absolute coordinates >>> dev.touch((0.5, 0.5)) # relative coordinates Returns: None ''' pass def double_click(self, pos): pass def swipe(self, p1, p2, duration=0.8, steps=5, button="left"): ''' Perform swipe (mouse press and mouse release) Args: p1: start point p2: end point duration: time interval to perform the swipe action steps: size of the swipe step button: mouse button to press, 'left', 'right' or 'middle', default is 'left' Examples: >>> from airtest.core.api import connect_device >>> dev = connect_device("Windows:///") >>> dev.swipe((100, 100), (200, 200), duration=0.5) >>> dev.swipe((0.1, 0.1), (0.2, 0.2), duration=0.5) Returns: None ''' pass def mouse_move(self, pos): '''Simulates a `mousemove` event. Known bug: Due to a bug in the pywinauto module, users might experience off-by-one errors when it comes to the exact coordinates of the position on screen. :param pos: A tuple (x, y), where x and y are x and y coordinates of the screen to move the mouse to, respectively. ''' pass def mouse_down(self, button='left'): '''Simulates a `mousedown` event. :param button: A string indicating which mouse button to be pressed. Available mouse button options are: {'left', 'middle', 'right'}. ''' pass def mouse_up(self, button='left'): '''Simulates a `mouseup` event. A call to the mouse_up() method usually follows a call to the mouse_down() method of the same mouse button. :param button: A string indicating which mouse button to be released. ''' pass def start_app(self, path, *args, **kwargs): ''' Start the application Args: path: full path to the application kwargs: reference: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.application.html#pywinauto.application.Application.start Returns: None ''' pass def stop_app(self, pid): ''' Stop the application Args: pid: process ID of the application to be stopped Returns: None ''' pass @require_app def set_foreground(self): ''' Bring the window foreground Returns: None ''' pass def get_rect(self): ''' Get rectangle Returns: win32structures.RECT ''' pass @require_app def get_title(self): ''' Get the window title Returns: window title ''' pass @require_app def get_pos(self): ''' Get the window position coordinates Returns: coordinates of topleft corner of the window (left, top) ''' pass @require_app def move(self, pos): ''' Move window to given coordinates Args: pos: coordinates (x, y) where to move the window Returns: None ''' pass @require_app def kill(self): ''' Kill the application Returns: None ''' pass def set_clipboard(self, text): ''' Set clipboard content Args: text: text to be set to clipboard Examples: >>> from airtest.core.api import connect_device >>> dev = connect_device("Windows:///") >>> dev.set_clipboard("hello world") >>> print(dev.get_clipboard()) 'hello world' >>> dev.paste() # paste the clipboard content Returns: None ''' pass def get_clipboard(self): ''' Get clipboard content Returns: clipboard content ''' pass def paste(self): ''' Perform paste action Returns: None ''' pass def _action_pos(self, pos): pass @property def focus_rect(self): pass @focus_rect.setter def focus_rect(self): pass def get_current_resolution(self): pass def _windowpos_to_screenpos(self, pos): ''' Convert given position relative to window topleft corner to screen coordinates Args: pos: coordinates (x, y) Returns: converted position coordinates ''' pass def get_ip_address(self): ''' Return default external ip address of the windows os. Returns: :py:obj:`str`: ip address ''' pass def start_recording(self, max_time=1800, output=None, fps=10, snapshot_sleep=0.001, orientation=0, max_size=None, *args, **kwargs): ''' Start recording the device display Args: max_time: maximum screen recording time, default is 1800 output: ouput file path mode: the backend write video, choose in ["ffmpeg"] ffmpeg: ffmpeg-python backend, higher compression rate. fps: frames per second will record snapshot_sleep: sleep time for each snapshot. orientation: 1: portrait, 2: landscape, 0: rotation. max_size: max size of the video frame, e.g.800, default is None. Smaller sizes lead to lower system load. Returns: save_path: path of video file Examples: Record 30 seconds of video and export to the current directory test.mp4: >>> from airtest.core.api import connect_device, sleep >>> dev = connect_device("Windows:///") >>> save_path = dev.start_recording(output="test.mp4") >>> sleep(30) >>> dev.stop_recording() >>> print(save_path) You can specify max_size to limit the video's maximum width/length. Smaller video sizes result in lower CPU load. >>> dev.start_recording(output="test.mp4", max_size=800) Note: 1 Don't resize the app window duraing recording, the recording region will be limited by first frame. 2 If recording still working after app crash, it will continuing write last frame before the crash. ''' pass def get_frame(): pass def stop_recording(self): ''' Stop recording the device display. Recoding file will be kept in the device. ''' pass
48
31
17
3
7
7
2
0.92
1
11
2
1
38
12
38
62
698
139
293
111
244
270
266
99
226
9
2
4
85
3,355
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/win/ctypesinput.py
airtest.core.win.ctypesinput.MouseInput
class MouseInput(ctypes.Structure): """ Contains information about a simulated mouse event. """ _fields_ = [('dx', LONG), ('dy', LONG), ('mouseData', DWORD), ('dwFlags', DWORD), ('time', DWORD), ('dwExtraInfo', ULONG_PTR)]
class MouseInput(ctypes.Structure): ''' Contains information about a simulated mouse event. ''' pass
1
1
0
0
0
0
0
0.43
0
0
0
0
0
0
0
0
10
0
7
2
6
3
2
2
1
0
0
0
0
3,356
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_touch_proxy.py
tests.test_touch_proxy.TestTouchProxy
class TestTouchProxy(unittest.TestCase): @classmethod def setUpClass(cls): cls.dev = Android() cls.dev.ori_method = "ADBORI" def test_auto_setup(self): touch_proxy = TouchProxy.auto_setup(self.dev.adb, ori_transformer=self.dev._touch_point_by_orientation, size_info=None, input_event=None) touch_proxy.touch((100, 100)) touch_proxy = TouchProxy.auto_setup(self.dev.adb, default_method="MINITOUCH", ori_transformer=self.dev._touch_point_by_orientation, size_info=self.dev.display_info, input_event=self.dev.input_event) touch_proxy.touch((100, 100)) def test_touch_method(self): self.assertIn(self.dev.touch_method, TouchProxy.TOUCH_METHODS.keys()) def test_get_deprecated_var(self): for name in ["minitouch", "maxtouch"]: obj = getattr(self.dev, name) self.assertIsInstance(obj, TouchProxy)
class TestTouchProxy(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_auto_setup(self): pass def test_touch_method(self): pass def test_get_deprecated_var(self): pass
6
0
6
0
5
0
1
0
1
2
2
0
3
0
4
76
27
4
23
9
17
0
15
8
10
2
2
1
5
3,357
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/device.py
airtest.core.device.MetaDevice
class MetaDevice(type): REGISTRY = {} def __new__(meta, name, bases, class_dict): cls = type.__new__(meta, name, bases, class_dict) meta.REGISTRY[name] = cls return cls
class MetaDevice(type): def __new__(meta, name, bases, class_dict): pass
2
0
4
0
4
0
1
0
1
0
0
0
1
0
1
14
8
2
6
4
4
0
6
4
4
1
2
0
1
3,358
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.AdbError
class AdbError(Exception): """ This is AdbError BaseError When ADB have something wrong """ def __init__(self, stdout, stderr): self.stdout = stdout self.stderr = stderr def __str__(self): return "stdout[%s] stderr[%s]" % (self.stdout, self.stderr)
class AdbError(Exception): ''' This is AdbError BaseError When ADB have something wrong ''' def __init__(self, stdout, stderr): pass def __str__(self): pass
3
1
3
0
3
0
1
0.67
1
0
0
1
2
2
2
12
11
1
6
5
3
4
6
5
3
1
3
0
2
3,359
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.AdbShellError
class AdbShellError(AdbError): """ adb shell error """ pass
class AdbShellError(AdbError): ''' adb shell error ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
12
5
0
2
1
1
3
2
1
1
0
4
0
0
3,360
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.AirtestError
class AirtestError(BaseError): """ This is Airtest BaseError """ pass
class AirtestError(BaseError): ''' This is Airtest BaseError ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
2
0
0
0
12
5
0
2
1
1
3
2
1
1
0
4
0
0
3,361
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.BaseError
class BaseError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
class BaseError(Exception): def __init__(self, value): pass def __str__(self): pass
3
0
2
0
2
0
1
0
1
0
0
8
2
1
2
12
6
1
5
4
2
0
5
4
2
1
3
0
2
3,362
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.DeviceConnectionError
class DeviceConnectionError(BaseError): """ device connection error """ DEVICE_CONNECTION_ERROR = r"error:\s*((device \'\S+\' not found)|(cannot connect to daemon at [\w\:\s\.]+ Connection timed out))" pass
class DeviceConnectionError(BaseError): ''' device connection error ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
6
0
3
2
2
3
3
2
2
0
4
0
0
3,363
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.ICmdError
class ICmdError(Exception): """ This is ICmdError BaseError When ICmd have something wrong """ def __init__(self, stdout, stderr): self.stdout = stdout self.stderr = stderr def __str__(self): return "stdout[%s] stderr[%s]" %(self.stdout, self.stderr)
class ICmdError(Exception): ''' This is ICmdError BaseError When ICmd have something wrong ''' def __init__(self, stdout, stderr): pass def __str__(self): pass
3
1
3
0
3
0
1
0.67
1
0
0
0
2
2
2
12
11
1
6
5
3
4
6
5
3
1
3
0
2
3,364
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.InvalidMatchingMethodError
class InvalidMatchingMethodError(BaseError): """ This is InvalidMatchingMethodError BaseError When an invalid matching method is used in settings. """ pass
class InvalidMatchingMethodError(BaseError): ''' This is InvalidMatchingMethodError BaseError When an invalid matching method is used in settings. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
12
6
0
2
1
1
4
2
1
1
0
4
0
0
3,365
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.LocalDeviceError
class LocalDeviceError(BaseError): """ Custom exception for calling a method on a non-local iOS device. """ def __init__(self, value="Can only use this method on a local device."): super().__init__(value)
class LocalDeviceError(BaseError): ''' Custom exception for calling a method on a non-local iOS device. ''' def __init__(self, value="Can only use this method on a local device."): pass
2
1
2
0
2
0
1
1
1
1
0
0
1
0
1
13
6
0
3
2
1
3
3
2
1
1
4
0
1
3,366
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.MinicapError
class MinicapError(ScreenError): """ This is MinicapError BaseError When Minicap have something wrong """ pass
class MinicapError(ScreenError): ''' This is MinicapError BaseError When Minicap have something wrong ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
12
6
0
2
1
1
4
2
1
1
0
5
0
0
3,367
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.MinitouchError
class MinitouchError(BaseError): """ This is MinitouchError BaseError When Minicap have something wrong """ pass
class MinitouchError(BaseError): ''' This is MinitouchError BaseError When Minicap have something wrong ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
12
6
0
2
1
1
4
2
1
1
0
4
0
0
3,368
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.NoDeviceError
class NoDeviceError(BaseError): """ When no device is connected """ pass
class NoDeviceError(BaseError): ''' When no device is connected ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
12
5
0
2
1
1
3
2
1
1
0
4
0
0
3,369
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.PerformanceError
class PerformanceError(BaseError): pass
class PerformanceError(BaseError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
12
2
0
2
1
1
0
2
1
1
0
4
0
0
3,370
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.ScreenError
class ScreenError(BaseError): """ When the screen capture method(Minicap/Javacap/ScreenProxy) has something wrong """ pass
class ScreenError(BaseError): ''' When the screen capture method(Minicap/Javacap/ScreenProxy) has something wrong ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
1
0
0
0
12
5
0
2
1
1
3
2
1
1
0
4
0
0
3,371
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_win_app.py
tests.test_win_app.TestWin
class TestWin(unittest.TestCase): @classmethod def setUpClass(cls): w = Windows() w.start_app("calc") time.sleep(1) cls.windows = Windows(title_re=".*计算器.*".decode("utf-8")) def test_snapshot(self): try_remove(SNAPSHOT) result = self.windows.snapshot(filename=SNAPSHOT) self.assertIsInstance(result, numpy.ndarray) try_remove(SNAPSHOT) def test_touch(self): self.windows.touch((11, 11)) def test_swipe(self): self.windows.swipe((11, 11), (100, 100)) def test_record(self): self.windows.start_recording(output="test_10s.mp4") time.sleep(10+4) self.windows.stop_recording() time.sleep(2) self.assertEqual(os.path.exists("test_10s.mp4"), True) duration = 0 cap = cv2.VideoCapture("test_10s.mp4") if cap.isOpened(): rate = cap.get(5) frame_num = cap.get(7) duration = frame_num/rate self.assertEqual(duration >= 10, True) @classmethod def tearDownClass(cls): cls.windows.app.kill() try_remove('test_10s.mp4') try_remove('test_cv_10s.mp4')
class TestWin(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_snapshot(self): pass def test_touch(self): pass def test_swipe(self): pass def test_record(self): pass @classmethod def tearDownClass(cls): pass
9
0
5
0
5
0
1
0
1
1
1
0
4
0
6
78
40
6
34
15
25
0
32
13
25
2
2
1
7
3,372
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/cv.py
airtest.core.cv.Template
class Template(object): """ picture as touch/swipe/wait/exists target and extra info for cv match filename: pic filename target_pos: ret which pos in the pic record_pos: pos in screen when recording resolution: screen resolution when recording rgb: 识别结果是否使用rgb三通道进行校验. scale_max: 多尺度模板匹配最大范围. scale_step: 多尺度模板匹配搜索步长. """ def __init__(self, filename, threshold=None, target_pos=TargetPos.MID, record_pos=None, resolution=(), rgb=False, scale_max=800, scale_step=0.005): self.filename = filename self._filepath = None self.threshold = threshold or ST.THRESHOLD self.target_pos = target_pos self.record_pos = record_pos self.resolution = resolution self.rgb = rgb self.scale_max = scale_max self.scale_step = scale_step @property def filepath(self): if self._filepath: return self._filepath for dirname in G.BASEDIR: filepath = os.path.join(dirname, self.filename) if os.path.isfile(filepath): self._filepath = filepath return self._filepath return self.filename def __repr__(self): filepath = self.filepath if PY3 else self.filepath.encode(sys.getfilesystemencoding()) return "Template(%s)" % filepath def match_in(self, screen): match_result = self._cv_match(screen) G.LOGGING.debug("match result: %s", match_result) if not match_result: return None focus_pos = TargetPos().getXY(match_result, self.target_pos) return focus_pos def match_all_in(self, screen): image = self._imread() image = self._resize_image(image, screen, ST.RESIZE_METHOD) return self._find_all_template(image, screen) @logwrap def _cv_match(self, screen): # in case image file not exist in current directory: ori_image = self._imread() image = self._resize_image(ori_image, screen, ST.RESIZE_METHOD) ret = None for method in ST.CVSTRATEGY: # get function definition and execute: func = MATCHING_METHODS.get(method, None) if func is None: raise InvalidMatchingMethodError("Undefined method in CVSTRATEGY: '%s', try 'kaze'/'brisk'/'akaze'/'orb'/'surf'/'sift'/'brief' instead." % method) else: if method in ["mstpl", "gmstpl"]: ret = self._try_match(func, ori_image, screen, threshold=self.threshold, rgb=self.rgb, record_pos=self.record_pos, resolution=self.resolution, scale_max=self.scale_max, scale_step=self.scale_step) else: ret = self._try_match(func, image, screen, threshold=self.threshold, rgb=self.rgb) if ret: break return ret @staticmethod def _try_match(func, *args, **kwargs): G.LOGGING.debug("try match with %s" % func.__name__) try: ret = func(*args, **kwargs).find_best_result() except aircv.NoModuleError as err: G.LOGGING.warning("'surf'/'sift'/'brief' is in opencv-contrib module. You can use 'tpl'/'kaze'/'brisk'/'akaze'/'orb' in CVSTRATEGY, or reinstall opencv with the contrib module.") return None except aircv.BaseError as err: G.LOGGING.debug(repr(err)) return None else: return ret def _imread(self): return aircv.imread(self.filepath) def _find_all_template(self, image, screen): return TemplateMatching(image, screen, threshold=self.threshold, rgb=self.rgb).find_all_results() def _find_keypoint_result_in_predict_area(self, func, image, screen): if not self.record_pos: return None # calc predict area in screen image_wh, screen_resolution = aircv.get_resolution(image), aircv.get_resolution(screen) xmin, ymin, xmax, ymax = Predictor.get_predict_area(self.record_pos, image_wh, self.resolution, screen_resolution) # crop predict image from screen predict_area = aircv.crop_image(screen, (xmin, ymin, xmax, ymax)) if not predict_area.any(): return None # keypoint matching in predicted area: ret_in_area = func(image, predict_area, threshold=self.threshold, rgb=self.rgb) # calc cv ret if found if not ret_in_area: return None ret = deepcopy(ret_in_area) if "rectangle" in ret: for idx, item in enumerate(ret["rectangle"]): ret["rectangle"][idx] = (item[0] + xmin, item[1] + ymin) ret["result"] = (ret_in_area["result"][0] + xmin, ret_in_area["result"][1] + ymin) return ret def _resize_image(self, image, screen, resize_method): """模板匹配中,将输入的截图适配成 等待模板匹配的截图.""" # 未记录录制分辨率,跳过 if not self.resolution: return image screen_resolution = aircv.get_resolution(screen) # 如果分辨率一致,则不需要进行im_search的适配: if tuple(self.resolution) == tuple(screen_resolution) or resize_method is None: return image if isinstance(resize_method, types.MethodType): resize_method = resize_method.__func__ # 分辨率不一致则进行适配,默认使用cocos_min_strategy: h, w = image.shape[:2] w_re, h_re = resize_method(w, h, self.resolution, screen_resolution) # 确保w_re和h_re > 0, 至少有1个像素: w_re, h_re = max(1, w_re), max(1, h_re) # 调试代码: 输出调试信息. G.LOGGING.debug("resize: (%s, %s)->(%s, %s), resolution: %s=>%s" % ( w, h, w_re, h_re, self.resolution, screen_resolution)) # 进行图片缩放: image = cv2.resize(image, (w_re, h_re)) return image
class Template(object): ''' picture as touch/swipe/wait/exists target and extra info for cv match filename: pic filename target_pos: ret which pos in the pic record_pos: pos in screen when recording resolution: screen resolution when recording rgb: 识别结果是否使用rgb三通道进行校验. scale_max: 多尺度模板匹配最大范围. scale_step: 多尺度模板匹配搜索步长. ''' def __init__(self, filename, threshold=None, target_pos=TargetPos.MID, record_pos=None, resolution=(), rgb=False, scale_max=800, scale_step=0.005): pass @property def filepath(self): pass def __repr__(self): pass def match_in(self, screen): pass def match_all_in(self, screen): pass @logwrap def _cv_match(self, screen): pass @staticmethod def _try_match(func, *args, **kwargs): pass def _imread(self): pass def _find_all_template(self, image, screen): pass def _find_keypoint_result_in_predict_area(self, func, image, screen): pass def _resize_image(self, image, screen, resize_method): '''模板匹配中,将输入的截图适配成 等待模板匹配的截图.''' pass
15
2
10
0
9
1
3
0.23
1
8
6
0
10
9
11
11
136
11
102
46
87
23
95
42
83
6
1
3
30
3,373
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/cv.py
airtest.core.cv.Predictor
class Predictor(object): """ this class predicts the press_point and the area to search im_search. """ DEVIATION = 100 @staticmethod def count_record_pos(pos, resolution): """计算坐标对应的中点偏移值相对于分辨率的百分比.""" _w, _h = resolution # 都按宽度缩放,针对G18的实验结论 delta_x = (pos[0] - _w * 0.5) / _w delta_y = (pos[1] - _h * 0.5) / _w delta_x = round(delta_x, 3) delta_y = round(delta_y, 3) return delta_x, delta_y @classmethod def get_predict_point(cls, record_pos, screen_resolution): """预测缩放后的点击位置点.""" delta_x, delta_y = record_pos _w, _h = screen_resolution target_x = delta_x * _w + _w * 0.5 target_y = delta_y * _w + _h * 0.5 return target_x, target_y @classmethod def get_predict_area(cls, record_pos, image_wh, image_resolution=(), screen_resolution=()): """Get predicted area in screen.""" x, y = cls.get_predict_point(record_pos, screen_resolution) # The prediction area should depend on the image size: if image_resolution: predict_x_radius = int(image_wh[0] * screen_resolution[0] / (2 * image_resolution[0])) + cls.DEVIATION predict_y_radius = int(image_wh[1] * screen_resolution[1] / (2 * image_resolution[1])) + cls.DEVIATION else: predict_x_radius, predict_y_radius = int(image_wh[0] / 2) + cls.DEVIATION, int(image_wh[1] / 2) + cls.DEVIATION area = (x - predict_x_radius, y - predict_y_radius, x + predict_x_radius, y + predict_y_radius) return area
class Predictor(object): ''' this class predicts the press_point and the area to search im_search. ''' @staticmethod def count_record_pos(pos, resolution): '''计算坐标对应的中点偏移值相对于分辨率的百分比.''' pass @classmethod def get_predict_point(cls, record_pos, screen_resolution): '''预测缩放后的点击位置点.''' pass @classmethod def get_predict_area(cls, record_pos, image_wh, image_resolution=(), screen_resolution=()): '''Get predicted area in screen.''' pass
7
4
9
0
7
2
1
0.3
1
1
0
0
0
0
3
3
39
4
27
19
20
8
23
16
19
2
1
1
4
3,374
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/touch_methods/touch_proxy.py
airtest.core.android.touch_methods.touch_proxy.MinitouchImplementation
class MinitouchImplementation(AdbTouchImplementation): METHOD_NAME = TOUCH_METHOD.MINITOUCH METHOD_CLASS = Minitouch def __init__(self, minitouch, ori_transformer): """ :param minitouch: :py:mod:`airtest.core.android.touch_methods.minitouch.Minitouch` :param ori_transformer: Android._touch_point_by_orientation() """ super(MinitouchImplementation, self).__init__(minitouch) self.ori_transformer = ori_transformer def touch(self, pos, duration=0.01): pos = self.ori_transformer(pos) self.base_touch.touch(pos, duration=duration) def swipe(self, p1, p2, duration=0.5, steps=5, fingers=1): p1 = self.ori_transformer(p1) p2 = self.ori_transformer(p2) if fingers == 1: self.base_touch.swipe(p1, p2, duration=duration, steps=steps) elif fingers == 2: self.base_touch.two_finger_swipe(p1, p2, duration=duration, steps=steps) else: raise Exception("param fingers should be 1 or 2") def pinch(self, center=None, percent=0.5, duration=0.5, steps=5, in_or_out='in'): if center: center = self.ori_transformer(center) self.base_touch.pinch(center=center, percent=percent, duration=duration, steps=steps, in_or_out=in_or_out) def swipe_along(self, coordinates_list, duration=0.8, steps=5): pos_list = [self.ori_transformer(xy) for xy in coordinates_list] self.base_touch.swipe_along(pos_list, duration=duration, steps=steps) def two_finger_swipe(self, tuple_from_xy, tuple_to_xy, duration=0.8, steps=5, offset=(0, 50)): tuple_from_xy = self.ori_transformer(tuple_from_xy) tuple_to_xy = self.ori_transformer(tuple_to_xy) self.base_touch.two_finger_swipe(tuple_from_xy, tuple_to_xy, duration=duration, steps=steps, offset=offset) def perform(self, motion_events, interval=0.01): self.base_touch.perform(motion_events, interval)
class MinitouchImplementation(AdbTouchImplementation): def __init__(self, minitouch, ori_transformer): ''' :param minitouch: :py:mod:`airtest.core.android.touch_methods.minitouch.Minitouch` :param ori_transformer: Android._touch_point_by_orientation() ''' pass def touch(self, pos, duration=0.01): pass def swipe(self, p1, p2, duration=0.5, steps=5, fingers=1): pass def pinch(self, center=None, percent=0.5, duration=0.5, steps=5, in_or_out='in'): pass def swipe_along(self, coordinates_list, duration=0.8, steps=5): pass def two_finger_swipe(self, tuple_from_xy, tuple_to_xy, duration=0.8, steps=5, offset=(0, 50)): pass def perform(self, motion_events, interval=0.01): pass
8
1
5
0
4
1
1
0.13
1
2
0
1
7
1
7
11
43
8
31
12
23
4
29
12
21
3
2
1
10
3,375
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/win/ctypesinput.py
airtest.core.win.ctypesinput.KeyBdInput
class KeyBdInput(ctypes.Structure): """ Contains information about a simulated keyboard event. """ _fields_ = [('wVk', WORD), ('wScan', WORD), ('dwFlags', DWORD), ('time', DWORD), ('dwExtraInfo', ULONG_PTR)]
class KeyBdInput(ctypes.Structure): ''' Contains information about a simulated keyboard event. ''' pass
1
1
0
0
0
0
0
0.5
0
0
0
0
0
0
0
0
9
0
6
2
5
3
2
2
1
0
0
0
0
3,376
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/win/ctypesinput.py
airtest.core.win.ctypesinput.Input
class Input(ctypes.Structure): """ Used by SendInput to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks. """ _anonymous_ = ('_input',) _fields_ = [('type', DWORD), ('_input', _Input)]
class Input(ctypes.Structure): ''' Used by SendInput to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks. ''' pass
1
1
0
0
0
0
0
1
0
0
0
0
0
0
0
0
8
0
4
3
3
4
3
3
2
0
0
0
0
3,377
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/win/ctypesinput.py
airtest.core.win.ctypesinput.HardwareInput
class HardwareInput(ctypes.Structure): """ Contains information about a simulated message generated by an input device other than a keyboard or mouse. """ _fields_ = [('uMsg', DWORD), ('wParamL', WORD), ('wParamH', WORD)]
class HardwareInput(ctypes.Structure): ''' Contains information about a simulated message generated by an input device other than a keyboard or mouse. ''' pass
1
1
0
0
0
0
0
1
0
0
0
0
0
0
0
0
8
0
4
2
3
4
2
2
1
0
0
0
0
3,378
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/constant.py
airtest.core.android.constant.IME_METHOD
class IME_METHOD(object): ADBIME = "ADBIME" YOSEMITEIME = "YOSEMITEIME"
class IME_METHOD(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
1
0
0
3,379
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/constant.py
airtest.core.android.constant.ORI_METHOD
class ORI_METHOD(object): ADB = "ADBORI" MINICAP = "MINICAPORI"
class ORI_METHOD(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
1
0
0
3,380
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/constant.py
airtest.core.android.constant.TOUCH_METHOD
class TOUCH_METHOD(object): MINITOUCH = "MINITOUCH" MAXTOUCH = "MAXTOUCH" ADBTOUCH = "ADBTOUCH"
class TOUCH_METHOD(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
1
0
0
3,381
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/ime.py
airtest.core.android.ime.YosemiteIme
class YosemiteIme(CustomIme): """ Yosemite Input Method Class Object """ def __init__(self, adb): super(YosemiteIme, self).__init__(adb, None, YOSEMITE_IME_SERVICE) self.yosemite = Yosemite(adb) def start(self): self.yosemite.get_ready() super(YosemiteIme, self).start() def text(self, value): """ Input text with Yosemite input method Args: value: text to be inputted Returns: output form `adb shell` command """ if not self.started: self.start() installed_version = self.adb.get_package_version(YOSEMITE_PACKAGE) if installed_version is not None and int(installed_version) >= int(430): local_port = self.adb.get_available_forward_local() self.adb.forward(local=f'tcp:{local_port}', remote="tcp:8181", no_rebind=False) for i in range(15): try: url = f'http://{self.adb.host}:{local_port}/ime_onStartInput' ret = requests.get(url, timeout=3) except Exception as e: time.sleep(1) if i % 3 == 0: # 超时未启动,再尝试启动 print(f"Trying to initialize input method again.") self.start() else: if 'ime_onStartInput=ok' in ret.text: self.adb.remove_forward(local=f'tcp:{local_port}') break else: self.adb.remove_forward(local=f'tcp:{local_port}') raise AdbError("IME Error", "IME initialization timed out.") # 更多的输入用法请见 https://github.com/macacajs/android-unicode#use-in-adb-shell value = ensure_unicode(value) value = escape_special_char(value) self.adb.shell(f"am broadcast -a ADB_INPUT_TEXT --es msg {value}") def code(self, code): """ Sending editor action Args: code: editor action code, e.g., 2 = IME_ACTION_GO, 3 = IME_ACTION_SEARCH Editor Action Code Ref: http://developer.android.com/reference/android/view/inputmethod/EditorInfo.html Returns: output form `adb shell` command """ if not self.started: self.start() self.adb.shell("am broadcast -a ADB_EDITOR_CODE --ei code {}".format(str(code)))
class YosemiteIme(CustomIme): ''' Yosemite Input Method Class Object ''' def __init__(self, adb): pass def start(self): pass def text(self, value): ''' Input text with Yosemite input method Args: value: text to be inputted Returns: output form `adb shell` command ''' pass def code(self, code): ''' Sending editor action Args: code: editor action code, e.g., 2 = IME_ACTION_GO, 3 = IME_ACTION_SEARCH Editor Action Code Ref: http://developer.android.com/reference/android/view/inputmethod/EditorInfo.html Returns: output form `adb shell` command ''' pass
5
3
15
2
9
4
2
0.54
1
7
2
0
4
1
4
11
67
11
37
12
32
20
37
11
32
5
2
5
9
3,382
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/win/ctypesinput.py
airtest.core.win.ctypesinput._Input
class _Input(ctypes.Union): _fields_ = [('ki', KeyBdInput), ('mi', MouseInput), ('hi', HardwareInput)]
class _Input(ctypes.Union): pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
4
0
4
2
3
0
2
2
1
0
0
0
0
3,383
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/rotation.py
airtest.core.android.rotation.XYTransformer
class XYTransformer(object): """ transform the coordinates (x, y) by orientation (upright <--> original) """ @staticmethod def up_2_ori(tuple_xy, tuple_wh, orientation): """ Transform the coordinates upright --> original Args: tuple_xy: coordinates (x, y) tuple_wh: screen width and height orientation: orientation Returns: transformed coordinates (x, y) """ x, y = tuple_xy w, h = tuple_wh if orientation == 1: x, y = w - y, x elif orientation == 2: x, y = w - x, h - y elif orientation == 3: x, y = y, h - x return x, y @staticmethod def ori_2_up(tuple_xy, tuple_wh, orientation): """ Transform the coordinates original --> upright Args: tuple_xy: coordinates (x, y) tuple_wh: screen width and height orientation: orientation Returns: transformed coordinates (x, y) """ x, y = tuple_xy w, h = tuple_wh if orientation == 1: x, y = y, w - x elif orientation == 2: x, y = w - x, h - y elif orientation == 3: x, y = h - y, x return x, y
class XYTransformer(object): ''' transform the coordinates (x, y) by orientation (upright <--> original) ''' @staticmethod def up_2_ori(tuple_xy, tuple_wh, orientation): ''' Transform the coordinates upright --> original Args: tuple_xy: coordinates (x, y) tuple_wh: screen width and height orientation: orientation Returns: transformed coordinates (x, y) ''' pass @staticmethod def ori_2_up(tuple_xy, tuple_wh, orientation): ''' Transform the coordinates original --> upright Args: tuple_xy: coordinates (x, y) tuple_wh: screen width and height orientation: orientation Returns: transformed coordinates (x, y) ''' pass
5
3
23
4
10
9
4
0.91
1
0
0
0
0
0
2
2
53
9
23
9
18
21
17
7
14
4
1
1
8
3,384
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/touch_methods/base_touch.py
airtest.core.android.touch_methods.base_touch.MoveEvent
class MoveEvent(MotionEvent): def __init__(self, coordinates, contact=0, pressure=50): """ Finger Move Event :param coordinates: finger move to coordinates in (x, y) :param contact: multi-touch action, starts from 0 :param pressure: touch pressure """ super(MoveEvent, self).__init__() self.coordinates = coordinates self.contact = contact self.pressure = pressure def getcmd(self, transform=None): if transform: x, y = transform(*self.coordinates) else: x, y = self.coordinates cmd = "m {contact} {x} {y} {pressure}\nc\n".format(contact=self.contact, x=x, y=y, pressure=self.pressure) return cmd
class MoveEvent(MotionEvent): def __init__(self, coordinates, contact=0, pressure=50): ''' Finger Move Event :param coordinates: finger move to coordinates in (x, y) :param contact: multi-touch action, starts from 0 :param pressure: touch pressure ''' pass def getcmd(self, transform=None): pass
3
1
9
0
6
3
2
0.46
1
1
0
0
2
3
2
3
20
1
13
8
10
6
12
8
9
2
2
1
3
3,385
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/touch_methods/base_touch.py
airtest.core.android.touch_methods.base_touch.SleepEvent
class SleepEvent(MotionEvent): def __init__(self, seconds): self.seconds = seconds def getcmd(self, transform=None): return None
class SleepEvent(MotionEvent): def __init__(self, seconds): pass def getcmd(self, transform=None): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
1
2
3
6
1
5
4
2
0
5
4
2
1
2
0
2
3,386
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/touch_methods/base_touch.py
airtest.core.android.touch_methods.base_touch.UpEvent
class UpEvent(MotionEvent): def __init__(self, contact=0): """ Finger Up Event :param contact: multi-touch action, starts from 0 """ super(UpEvent, self).__init__() self.contact = contact def getcmd(self, transform=None): cmd = "u {:.0f}\nc\n".format(self.contact) return cmd
class UpEvent(MotionEvent): def __init__(self, contact=0): ''' Finger Up Event :param contact: multi-touch action, starts from 0 ''' pass def getcmd(self, transform=None): pass
3
1
5
0
3
2
1
0.57
1
1
0
0
2
1
2
3
12
1
7
5
4
4
7
5
4
1
2
0
2
3,387
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/touch_methods/maxtouch.py
airtest.core.android.touch_methods.maxtouch.Maxtouch
class Maxtouch(BaseTouch): def __init__(self, adb, backend=False, size_info=None, input_event=None): super(Maxtouch, self).__init__(adb, backend, size_info, input_event) self.default_pressure = 0.5 self.path_in_android = "/data/local/tmp/maxpresent.jar" self.localport = None def install(self): """ Install maxtouch Returns: None """ try: exists_file = self.adb.file_size(self.path_in_android) except: pass else: local_minitouch_size = int(os.path.getsize(MAXTOUCH_JAR)) if exists_file and exists_file == local_minitouch_size: LOGGING.debug("install_maxtouch skipped") return self.uninstall() self.adb.push(MAXTOUCH_JAR, self.path_in_android) self.adb.shell("chmod 755 %s" % self.path_in_android) LOGGING.info("install maxpresent.jar finished") def uninstall(self): """ Uninstall maxtouch Returns: None """ self.adb.raw_shell("rm %s" % self.path_in_android) def setup_server(self): """ Setup maxtouch server and adb forward Returns: server process """ if self.server_proc: self.server_proc.kill() self.server_proc = None self.localport, deviceport = self.adb.setup_forward("localabstract:maxpresent_{}".format) deviceport = deviceport[len("localabstract:"):] p = self.adb.start_shell("app_process -Djava.class.path={0} /data/local/tmp com.netease.maxpresent.MaxPresent socket {1}".format(self.path_in_android, deviceport)) nbsp = NonBlockingStreamReader(p.stdout, name="airtouch_server", auto_kill=True) line = nbsp.readline(timeout=5.0) if line is None: kill_proc(p) raise RuntimeError("airtouch setup timeout") if p.poll() is not None: # server setup error, may be already setup by others # subprocess exit immediately kill_proc(p) raise RuntimeError("airtouch server quit immediately") self.server_proc = p return p def setup_client(self): """ Setup client Returns: None """ s = SafeSocket() s.connect((self.adb.host, self.localport)) s.sock.settimeout(2) self.client = s self.handle = self.safe_send def transform_xy(self, x, y): """ Normalized coordinates (x, y) Args: x: coordinate x y: coordinate y Returns: transformed coordinates (x, y) """ width, height = self.size_info['width'], self.size_info['height'] return x / width, y / height def teardown(self): super(Maxtouch, self).teardown() if self.localport: self.adb.remove_forward("tcp:{}".format(self.localport)) self.localport = None
class Maxtouch(BaseTouch): def __init__(self, adb, backend=False, size_info=None, input_event=None): pass def install(self): ''' Install maxtouch Returns: None ''' pass def uninstall(self): ''' Uninstall maxtouch Returns: None ''' pass def setup_server(self): ''' Setup maxtouch server and adb forward Returns: server process ''' pass def setup_client(self): ''' Setup client Returns: None ''' pass def transform_xy(self, x, y): ''' Normalized coordinates (x, y) Args: x: coordinate x y: coordinate y Returns: transformed coordinates (x, y) ''' pass def teardown(self): pass
8
5
14
2
7
4
2
0.57
1
5
2
0
7
6
7
26
105
22
53
22
45
30
53
22
45
4
2
2
13
3,388
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/touch_methods/minitouch.py
airtest.core.android.touch_methods.minitouch.Minitouch
class Minitouch(BaseTouch): def __init__(self, adb, backend=False, size_info=None, input_event=None): super(Minitouch, self).__init__(adb, backend, size_info, input_event) self.default_pressure = 50 self.path_in_android = "/data/local/tmp/minitouch" self.max_x, self.max_y = None, None self.localport = None def install(self): """ Install minitouch Returns: None """ abi = self.adb.getprop("ro.product.cpu.abi") sdk = int(self.adb.getprop("ro.build.version.sdk")) if sdk >= 16: binfile = "minitouch" else: binfile = "minitouch-nopie" device_dir = os.path.dirname(self.path_in_android) path = os.path.join(STFLIB, abi, binfile).replace("\\", r"\\") try: exists_file = self.adb.file_size(self.path_in_android) except: pass else: local_minitouch_size = int(os.path.getsize(path)) if exists_file and exists_file == local_minitouch_size: LOGGING.debug("install_minitouch skipped") return self.uninstall() self.adb.push(path, "%s/minitouch" % device_dir) self.adb.shell("chmod 755 %s/minitouch" % (device_dir)) LOGGING.info("install_minitouch finished") def uninstall(self): """ Uninstall minitouch Returns: None """ self.adb.raw_shell("rm " + self.path_in_android) def setup_server(self): """ Setup minitouch server and adb forward Returns: server process """ if self.server_proc: self.server_proc.kill() self.server_proc = None self.localport, deviceport = self.adb.setup_forward("localabstract:minitouch_{}".format) deviceport = deviceport[len("localabstract:"):] if self.input_event: p = self.adb.start_shell("/data/local/tmp/minitouch -n '{0}' -d '{1}' 2>&1".format(deviceport,self.input_event)) else: p = self.adb.start_shell("/data/local/tmp/minitouch -n '{0}' 2>&1".format(deviceport)) nbsp = NonBlockingStreamReader(p.stdout, name="minitouch_server", auto_kill=True) while True: line = nbsp.readline(timeout=3.0) if line is None: kill_proc(p) raise RuntimeError("minitouch setup timeout") line = line.decode(get_std_encoding(sys.stdout)) # 识别出setup成功的log,并匹配出max_x, max_y m = re.search("Type \w touch device .+ \((\d+)x(\d+) with \d+ contacts\) detected on .+ \(.+\)", line) if m: self.max_x, self.max_y = int(m.group(1)), int(m.group(2)) break else: self.max_x = 32768 self.max_y = 32768 if p.poll() is not None: # server setup error, may be already setup by others # subprocess exit immediately kill_proc(p) raise RuntimeError("minitouch server quit immediately") self.server_proc = p reg_cleanup(kill_proc, self.server_proc) return p def setup_client(self): """ Setup client in following steps:: 1. connect to server 2. receive the header v <version> ^ <max-contacts> <max-x> <max-y> <max-pressure> $ <pid> 3. prepare to send Returns: None """ s = SafeSocket() s.connect((self.adb.host, self.localport)) s.sock.settimeout(2) header = b"" while True: try: header += s.sock.recv(4096) # size is not strict, so use raw socket.recv except socket.timeout: # raise RuntimeError("minitouch setup client error") warnings.warn("minitouch header not recved") break if header.count(b'\n') >= 3: break LOGGING.debug("minitouch header:%s", repr(header)) self.client = s self.handle = self.safe_send def transform_xy(self, x, y): """ Transform coordinates (x, y) according to the device display Args: x: coordinate x y: coordinate y Returns: transformed coordinates (x, y) """ width, height = self.size_info['width'], self.size_info['height'] nx = float(x) * self.max_x / width ny = float(y) * self.max_y / height return "%.0f" % nx, "%.0f" % ny def teardown(self): super(Minitouch, self).teardown() if self.localport: self.adb.remove_forward("tcp:{}".format(self.localport)) self.localport = None
class Minitouch(BaseTouch): def __init__(self, adb, backend=False, size_info=None, input_event=None): pass def install(self): ''' Install minitouch Returns: None ''' pass def uninstall(self): ''' Uninstall minitouch Returns: None ''' pass def setup_server(self): ''' Setup minitouch server and adb forward Returns: server process ''' pass def setup_client(self): ''' Setup client in following steps:: 1. connect to server 2. receive the header v <version> ^ <max-contacts> <max-x> <max-y> <max-pressure> $ <pid> 3. prepare to send Returns: None ''' pass def transform_xy(self, x, y): ''' Transform coordinates (x, y) according to the device display Args: x: coordinate x y: coordinate y Returns: transformed coordinates (x, y) ''' pass def teardown(self): pass
8
5
21
3
12
6
3
0.45
1
6
2
0
7
8
7
26
152
27
87
32
79
39
84
32
76
7
2
2
20
3,389
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/touch_methods/touch_proxy.py
airtest.core.android.touch_methods.touch_proxy.AdbTouchImplementation
class AdbTouchImplementation(object): METHOD_NAME = TOUCH_METHOD.ADBTOUCH def __init__(self, base_touch): """ :param base_touch: :py:mod:`airtest.core.android.adb.ADB` """ self.base_touch = base_touch def touch(self, pos, duration=0.01): if duration <= 0.01: self.base_touch.touch(pos) else: self.swipe(pos, pos, duration=duration) def swipe(self, p1, p2, duration=0.5, *args, **kwargs): duration *= 1000 self.base_touch.swipe(p1, p2, duration=duration) def teardown(self): pass
class AdbTouchImplementation(object): def __init__(self, base_touch): ''' :param base_touch: :py:mod:`airtest.core.android.adb.ADB` ''' pass def touch(self, pos, duration=0.01): pass def swipe(self, p1, p2, duration=0.5, *args, **kwargs): pass def teardown(self): pass
5
1
4
0
3
1
1
0.21
1
0
0
1
4
1
4
4
22
5
14
7
9
3
13
7
8
2
1
1
5
3,390
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/touch_methods/touch_proxy.py
airtest.core.android.touch_methods.touch_proxy.MaxtouchImplementation
class MaxtouchImplementation(MinitouchImplementation): METHOD_NAME = TOUCH_METHOD.MAXTOUCH METHOD_CLASS = Maxtouch def __init__(self, maxtouch, ori_transformer): """ New screen click scheme, support Android10 新的屏幕点击方案,支持Android10以上版本 :param maxtouch: :py:mod:`airtest.core.android.touch_methods.maxtouch.Maxtouch` :param ori_transformer: Android._touch_point_by_orientation() """ super(MaxtouchImplementation, self).__init__(maxtouch, ori_transformer) def perform(self, motion_events, interval=0.01): self.base_touch.perform(motion_events, interval)
class MaxtouchImplementation(MinitouchImplementation): def __init__(self, maxtouch, ori_transformer): ''' New screen click scheme, support Android10 新的屏幕点击方案,支持Android10以上版本 :param maxtouch: :py:mod:`airtest.core.android.touch_methods.maxtouch.Maxtouch` :param ori_transformer: Android._touch_point_by_orientation() ''' pass def perform(self, motion_events, interval=0.01): pass
3
1
6
1
2
3
1
0.86
1
1
0
0
2
0
2
13
16
3
7
5
4
6
7
5
4
1
3
0
2
3,391
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/android/touch_methods/base_touch.py
airtest.core.android.touch_methods.base_touch.DownEvent
class DownEvent(MotionEvent): def __init__(self, coordinates, contact=0, pressure=50): """ Finger Down Event :param coordinates: finger down coordinates in (x, y) :param contact: multi-touch action, starts from 0 :param pressure: touch pressure """ super(DownEvent, self).__init__() self.coordinates = coordinates self.contact = contact self.pressure = pressure def getcmd(self, transform=None): if transform: x, y = transform(*self.coordinates) else: x, y = self.coordinates cmd = "d {contact} {x} {y} {pressure}\nc\n".format(contact=self.contact, x=x, y=y, pressure=self.pressure) return cmd
class DownEvent(MotionEvent): def __init__(self, coordinates, contact=0, pressure=50): ''' Finger Down Event :param coordinates: finger down coordinates in (x, y) :param contact: multi-touch action, starts from 0 :param pressure: touch pressure ''' pass def getcmd(self, transform=None): pass
3
1
9
0
6
3
2
0.46
1
1
0
0
2
3
2
3
20
1
13
8
10
6
12
8
9
2
2
1
3
3,392
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_motionevents.py
tests.test_motionevents.TestMotionEvents
class TestMotionEvents(unittest.TestCase): @classmethod def setUpClass(cls): cls.device = Android() @classmethod def tearDownClass(cls): pass def test_multi_touch(self): """ 测试两指同时点击 """ multitouch_event = [ DownEvent((100, 100), 0), DownEvent((300, 300), 1), # second finger SleepEvent(1), UpEvent(0), UpEvent(1)] self.device.touch_proxy.perform(multitouch_event) def test_swipe(self): """ 测试滑动 """ swipe_event = [DownEvent((500, 500)), SleepEvent(0.1)] for i in range(5): swipe_event.append(MoveEvent((500 + 100 * i, 500 + 100 * i))) swipe_event.append(SleepEvent(0.2)) swipe_event.append(UpEvent()) self.device.touch_proxy.perform(swipe_event) def test_retry_touch(self): """ 测试在指令内容异常时,能够自动尝试重连 """ # 在安卓10部分型号手机上,如果乱序发送指令,可能会导致maxtouch断开连接 events = [MoveEvent((100, 100), 0), UpEvent(), DownEvent((165, 250), 0), SleepEvent(0.2), UpEvent(), DownEvent((165, 250), 0), SleepEvent(0.2), UpEvent()] self.device.touch_proxy.perform(events) time.sleep(3) self.device.touch((165, 250)) def test_horizontal(self): """ 如果设备是横屏,必须要加上坐标转换(竖屏也可以加) """ ori_transformer = self.device.touch_proxy.ori_transformer touch_landscape_point = [DownEvent(ori_transformer((100, 100))), SleepEvent(1), UpEvent()] self.device.touch_proxy.perform(touch_landscape_point)
class TestMotionEvents(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_multi_touch(self): ''' 测试两指同时点击 ''' pass def test_swipe(self): ''' 测试滑动 ''' pass def test_retry_touch(self): ''' 测试在指令内容异常时,能够自动尝试重连 ''' pass def test_horizontal(self): ''' 如果设备是横屏,必须要加上坐标转换(竖屏也可以加) ''' pass
9
4
8
1
5
2
1
0.47
1
6
5
0
4
0
6
78
54
11
30
15
21
14
24
13
17
2
2
1
7
3,393
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/minicap.py
airtest.core.ios.minicap.MinicapIOS
class MinicapIOS(object): """https://github.com/openstf/ios-minicap""" CAPTIMEOUT = None def __init__(self, udid=None, port=12345): super(MinicapIOS, self).__init__() self.udid = udid or list_devices()[0] print(repr(self.udid)) self.port = port self.resolution = "320x568" self.executable = os.path.join(os.path.dirname(__file__), "ios_minicap") self.server_proc = None def setup(self): cmd = [self.executable, "--udid", self.udid, "--port", str(self.port), "--resolution", self.resolution] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, creationflags=SUBPROCESS_FLAG) nbsp = NonBlockingStreamReader(proc.stdout, print_output=True, name="minicap_sever") while True: line = nbsp.readline(timeout=10.0) if line is None: raise RuntimeError("minicap setup error") if b"== Banner ==" in line: break if proc.poll() is not None: logging.warn("Minicap server already started, use old one") self.server_proc = proc def get_frames(self): """ rotation is alwary right on iOS """ s = SafeSocket() s.connect(("localhost", self.port)) t = s.recv(24) # minicap info print(struct.unpack("<2B5I2B", t)) while True: # recv header, count frame_size if self.CAPTIMEOUT is not None: header = s.recv_with_timeout(4, self.CAPTIMEOUT) else: header = s.recv(4) if header is None: LOGGING.error("minicap header is None") # recv timeout, if not frame updated, maybe screen locked yield None else: frame_size = struct.unpack("<I", header)[0] # recv image data one_frame = s.recv(frame_size) yield one_frame s.close()
class MinicapIOS(object): '''https://github.com/openstf/ios-minicap''' def __init__(self, udid=None, port=12345): pass def setup(self): pass def get_frames(self): ''' rotation is alwary right on iOS ''' pass
4
2
16
0
13
2
3
0.19
1
6
2
0
3
5
3
3
55
5
42
19
38
8
39
19
35
5
1
2
10
3,394
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/ios.py
airtest.core.ios.ios.IOS
class IOS(Device): """IOS client. - before this you have to run `WebDriverAgent <https://github.com/AirtestProject/iOS-Tagent>`_ - ``xcodebuild -project path/to/WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination "id=$(idevice_id -l)" test`` - ``iproxy $port 8100 $udid`` """ def __init__(self, addr=DEFAULT_ADDR, cap_method=CAP_METHOD.MJPEG, mjpeg_port=None, udid=None, name=None, serialno=None, wda_bundle_id=None): super().__init__() # If none or empty, use default addr. self.addr = addr or DEFAULT_ADDR # Fit wda format, make url start with http://, # e.g., http://localhost:8100/ or http+usbmux://00008020-001270842E88002E # with mjpeg_port: http://localhost:8100/?mjpeg_port=9100 # with udid(udid/uuid/serialno are all ok): http://localhost:8100/?mjpeg_port=9100&&udid=00008020-001270842E88002E. if not self.addr.startswith("http"): self.addr = "http://" + addr # Here now use these supported cap touch and ime method. self.cap_method = cap_method self.touch_method = TOUCH_METHOD.WDATOUCH self.ime_method = IME_METHOD.WDAIME # Wda driver, use to home, start app, click/swipe/close app/get wda size. # Init wda session, updata when start app. wda.DEBUG = False # The three connection modes are determined by the addr. # e.g., connect remote device http://10.227.70.247:20042 # e.g., connect local device http://127.0.0.1:8100 or http://localhost:8100 or http+usbmux://00008020-001270842E88002E self.udid = udid or name or serialno self._wda_bundle_id = wda_bundle_id parsed = urlparse(self.addr).netloc.split(":")[0] if ":" in urlparse(self.addr).netloc else urlparse( self.addr).netloc if parsed not in ["localhost", "127.0.0.1"] and "." in parsed: # Connect remote device via url. self.is_local_device = False self.driver = wda.Client(self.addr) else: # Connect local device via url. self.is_local_device = True if parsed in ["localhost", "127.0.0.1"]: if not udid: udid = self._get_default_device() self.udid = udid else: self.udid = parsed self.driver = wda.USBClient(udid=self.udid, port=8100, wda_bundle_id=self.wda_bundle_id) # Record device's width and height. self._size = {'width': None, 'height': None} self._current_orientation = None self._touch_factor = None self._last_orientation = None self._is_pad = None self._using_ios_tagent = None self._device_info = {} self.instruct_helper = InstructHelper(self.device_info['uuid']) self.mjpegcap = MJpegcap(self.instruct_helper, ori_function=lambda: self.display_info, ip=self.ip, port=mjpeg_port) # Start up RotationWatcher with default session. self.rotation_watcher = RotationWatcher(self) self._register_rotation_watcher() self.alert_watch_and_click = self.driver.alert.watch_and_click # Recorder. self.recorder = None # Since uuid and udid are very similar, both names are allowed. self._udid = udid or name or serialno def _get_default_device(self): """Get local default device when no udid. Returns: Local device udid. """ device_udid_list = TIDevice.devices() if device_udid_list: return device_udid_list[0] raise IndexError("iOS devices not found, please connect device first.") def _get_default_wda_bundle_id(self): """Get local default device's WDA bundleID when no WDA bundleID. Returns: Local device's WDA bundleID. """ try: wda_list = TIDevice.list_wda(self.udid) return wda_list[0] except IndexError: raise IndexError("WDA bundleID not found, please install WDA on device.") def _get_default_running_wda_bundle_id(self): """Get the bundleID of the WDA that is currently running on local device. Returns: Local device's running WDA bundleID. """ try: running_wda_list = TIDevice.ps_wda(self.udid) return running_wda_list[0] except IndexError: raise IndexError("Running WDA bundleID not found, please makesure WDA was started.") @property def wda_bundle_id(self): if not self._wda_bundle_id and self.is_local_device: self._wda_bundle_id = self._get_default_wda_bundle_id() return self._wda_bundle_id @property def ip(self): """Returns the IP address of the host connected to the iOS phone. It is not the IP address of the iOS phone. If you want to get the IP address of the phone, you can access the interface `get_ip_address`. For example: when the device is connected via http://localhost:8100, return localhost. If it is a remote device http://192.168.xx.xx:8100, it returns the IP address of 192.168.xx.xx. Returns: IP. """ match = re.search(IP_PATTERN, self.addr) if match: ip = match.group(0) else: ip = 'localhost' return ip @property def uuid(self): return self._udid or self.addr @property def using_ios_tagent(self): """ 当前基础版本:appium/WebDriverAgent 4.1.4 基于上述版本,2022.3.30之后发布的iOS-Tagent版本,在/status接口中新增了一个Version参数,如果能检查到本参数,说明使用了新版本ios-Tagent 该版本基于Appium版的WDA做了一些改动,可以更快地进行点击和滑动,并优化了部分UI树的获取逻辑 但是所有的坐标都为竖屏坐标,需要airtest自行根据方向做转换 同时,大于4.1.4版本的appium/WebDriverAgent不再需要针对ipad进行特殊的横屏坐标处理了 Returns: True if using ios-tagent, else False. """ if self._using_ios_tagent is None: status = self.driver.status() if 'Version' in status: self._using_ios_tagent = True else: self._using_ios_tagent = False return self._using_ios_tagent def _fetch_new_session(self): """Re-acquire a new session. """ # 根据facebook-wda的逻辑,直接设为None就会自动获取一个新的默认session self.driver.session_id = None @property def is_pad(self): """ Determine whether it is an ipad(or 6P/7P/8P), if it is, in the case of horizontal screen + desktop, the coordinates need to be switched to vertical screen coordinates to click correctly (WDA bug). 判断是否是ipad(或 6P/7P/8P),如果是,在横屏+桌面的情况下,坐标需要切换成竖屏坐标才能正确点击(WDA的bug) Returns: True if it is an ipad, else False. """ if self._is_pad is None: info = self.device_info if info["model"] == "iPad" or \ (self.display_info["width"], self.display_info["height"]) in LANDSCAPE_PAD_RESOLUTION: # ipad与6P/7P/8P等设备,桌面横屏时的表现一样,都会变横屏 self._is_pad = True else: self._is_pad = False return self._is_pad @property def device_info(self): """ Get the device info. Notes: Might not work on all devices. Returns: Dict for device info, e.g. AttrDict({ 'timeZone': 'GMT+0800', 'currentLocale': 'zh_CN', 'model': 'iPhone', 'uuid': '90CD6AB7-11C7-4E52-B2D3-61FA31D791EC', 'userInterfaceIdiom': 0, 'userInterfaceStyle': 'light', 'name': 'iPhone', 'isSimulator': False}) """ if not self._device_info: device_info = self.driver.info try: # Add some device info. if not self.is_local_device: raise LocalDeviceError() tmp_dict = TIDevice.device_info(self.udid) device_info.update(tmp_dict) except: pass finally: self._device_info = device_info return self._device_info def _register_rotation_watcher(self): """ Register callbacks for Android and minicap when rotation of screen has changed, callback is called in another thread, so be careful about thread-safety. """ self.rotation_watcher.reg_callback(lambda x: setattr(self, "_current_orientation", x)) def window_size(self): """ Returns: Window size (width, height). """ try: return self.driver.window_size() except wda.exceptions.WDAStaleElementReferenceError: print("iOS connection failed, please try pressing the home button to return to the desktop and try again.") print("iOS连接失败,请尝试按home键回到桌面后再重试") raise @property def orientation(self): """ Returns: Device orientation status in LANDSACPE POR. """ if not self._current_orientation: self._current_orientation = self.get_orientation() return self._current_orientation @orientation.setter def orientation(self, value): """ Args: value(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT | UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN """ # 可以对屏幕进行旋转,但是可能会导致问题 self.driver.orientation = value def get_orientation(self): # self.driver.orientation只能拿到LANDSCAPE,不能拿到左转/右转的确切方向 # 因此手动调用/rotation获取屏幕实际方向 rotation = self.driver._session_http.get('/rotation') # rotation dict eg. {'value': {'x': 0, 'y': 0, 'z': 90}, 'sessionId': 'xx', 'status': 0} if rotation: return ROTATION_MODE.get(rotation['value']['z'], wda.PORTRAIT) @property def display_info(self): if not self._size['width'] or not self._size['height']: self._display_info() self._size['orientation'] = self.orientation return self._size def _display_info(self): # Function window_size() return UIKit size, while screenshot() image size is Native Resolution. window_size = self.window_size() # When use screenshot, the image size is pixels size. e.g.(1080 x 1920) snapshot = self.snapshot() if self.orientation in [wda.LANDSCAPE, wda.LANDSCAPE_RIGHT]: self._size['window_width'], self._size['window_height'] = window_size.height, window_size.width width, height = snapshot.shape[:2] else: self._size['window_width'], self._size['window_height'] = window_size.width, window_size.height height, width = snapshot.shape[:2] self._size["width"] = width self._size["height"] = height # Use session.scale can get UIKit scale factor. # So self._touch_factor = 1 / self.driver.scale, but the result is incorrect on some devices(6P/7P/8P). self._touch_factor = float(self._size['window_height']) / float(height) self.rotation_watcher.get_ready() # 当前版本: wda 4.1.4 获取到的/window/size,在ipad+桌面横屏下拿到的是 height * height,需要修正。 if self.is_pad and self.home_interface(): self._size['window_width'] = int(width * self._touch_factor) @property def touch_factor(self): if not self._touch_factor: self._display_info() return self._touch_factor @touch_factor.setter def touch_factor(self, factor): """ Func touch_factor is used to convert click coordinates: mobile phone real coordinates = touch_factor * screen coordinates. In general, no manual settings are required. touch_factor用于换算点击坐标:手机真实坐标 = touch_factor * 屏幕坐标 默认计算方式是: self.display_info['window_height'] / self.display_info['height'] 但在部分特殊型号手机上可能不准确,例如iOS14.4的7P,默认值为 1/3,但部分7P点击位置不准确,可自行设置为:self.touch_factor = 1 / 3.3 (一般情况下,无需手动设置!) Examples: >>> device = connect_device("iOS:///") >>> device.touch((100, 100)) # wrong position >>> print(device.touch_factor) 0.333333 >>> device.touch_factor = 1 / 3.3 # default is 1/3 >>> device.touch((100, 100)) Args: factor: real_pos / pixel_pos, e.g: 1/self.driver.scale """ self._touch_factor = float(factor) def get_render_resolution(self): """Return render resolution after rotation. Returns: offset_x, offset_y, offset_width and offset_height of the display. """ w, h = self.get_current_resolution() return 0, 0, w, h def get_current_resolution(self): w, h = self.display_info["width"], self.display_info["height"] if self.display_info["orientation"] in [wda.LANDSCAPE, wda.LANDSCAPE_RIGHT]: w, h = h, w return w, h def home(self): # Press("home") faster than home(). return self.driver.press("home") def _neo_wda_screenshot(self): """ This is almost same as wda implementation, but without png header check, as response data is now jpg format in mid quality. """ value = self.driver.http.get('screenshot').value raw_value = base64.b64decode(value) return raw_value def snapshot(self, filename=None, quality=10, max_size=None): """Take snapshot. Args: filename: save screenshot to filename quality: The image quality, integer in range [1, 99] max_size: the maximum size of the picture, e.g 1200 Returns: Screen snapshot's cv2 object. """ data = self._neo_wda_screenshot() # Output cv2 object. try: screen = aircv.utils.string_2_img(data) except: # May be black/locked screen or other reason, print exc for debugging. traceback.print_exc() return None # Save as file if needed. if filename: aircv.imwrite(filename, screen, quality, max_size=max_size) return screen def get_frame_from_stream(self): if self.cap_method == CAP_METHOD.MJPEG: try: return self.mjpegcap.get_frame_from_stream() except ConnectionRefusedError: self.cap_method = CAP_METHOD.WDACAP return self._neo_wda_screenshot() def touch(self, pos, duration=0.01): """ Args: pos: coordinates (x, y), can be float(percent) or int duration (optional): tap_hold duration Returns: None(iOS may all use vertical screen coordinates, so coordinates will not be returned.) Examples: >>> touch((100, 100)) >>> touch((0.5, 0.5), duration=1) """ x, y = pos if not (x < 1 and y < 1): x, y = int(x * self.touch_factor), int(y * self.touch_factor) # 根据用户安装的wda版本判断是否调用快速点击接口 if self.using_ios_tagent: x, y = self._transform_xy(pos) self._quick_click(x, y, duration) else: self.driver.click(x, y, duration) def _quick_click(self, x, y, duration): """ The method extended from the facebook-wda third-party library. Use modified appium wda to perform quick click. Args: x, y (int, float): float(percent), int(coordicate) duration (optional): tap_hold duration """ x, y = self.driver._percent2pos(x, y) data = {'x': x, 'y': y, 'duration': duration} # 为了兼容改动直接覆盖原生接口的自制版wda。 try: self.driver._session_http.post('/wda/deviceTap', data=data) # 如果找不到接口说明是低版本的wda,低于1.3版本没有此接口 except wda.WDARequestError as e: try: return self.driver._session_http.post('/wda/tap', data=data) except wda.WDARequestError as e: if e.status == 110: self.driver.click(x, y, duration) def double_click(self, pos): x, y = self._transform_xy(pos) self.driver.double_tap(x, y) def swipe(self, fpos, tpos, duration=0, delay=None, *args, **kwargs): """ Args: fpos: start point tpos: end point duration (float): start coordinate press duration (seconds), default is None delay (float): start coordinate to end coordinate duration (seconds) Returns: None Examples: >>> swipe((1050, 1900), (150, 1900)) >>> swipe((0.2, 0.5), (0.8, 0.5)) """ fx, fy = fpos tx, ty = tpos if not (fx < 1 and fy < 1): fx, fy = int(fx * self.touch_factor), int(fy * self.touch_factor) if not (tx < 1 and ty < 1): tx, ty = int(tx * self.touch_factor), int(ty * self.touch_factor) # 如果是通过ide来滑动,且安装的是自制版的wda就调用快速滑动接口,其他时候不关心滑动速度就使用原生接口保证滑动精确性。 def ios_tagent_swipe(fpos, tpos, delay=None): # 调用自定义的wda swipe接口需要进行坐标转换。 fx, fy = self._transform_xy(fpos) tx, ty = self._transform_xy(tpos) self._quick_swipe(fx, fy, tx, ty, delay or 0.2) if delay: if self.using_ios_tagent: ios_tagent_swipe(fpos, tpos, delay) else: self.driver.swipe(fx, fy, tx, ty) else: try: self.driver.swipe(fx, fy, tx, ty, duration) except wda.WDARequestError as e: if e.status == 110: # 部分低版本iOS在滑动时,可能会有报错,调用一次ios-Tagent的快速滑动接口来尝试解决 if self.using_ios_tagent: ios_tagent_swipe(fpos, tpos, delay) else: raise def _quick_swipe(self, x1, y1, x2, y2, delay): """ The method extended from the facebook-wda third-party library. Use modified appium wda to perform quick swipe. Args: x1, y1, x2, y2 (int, float): float(percent), int(coordicate) delay (float): start coordinate to end coordinate duration (seconds) """ if any(isinstance(v, float) for v in [x1, y1, x2, y2]): size = self.window_size() x1, y1 = self.driver._percent2pos(x1, y1, size) x2, y2 = self.driver._percent2pos(x2, y2, size) data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, delay=delay) # 为了兼容改动直接覆盖原生接口的自制版wda。 try: if self.using_ios_tagent: try: self.driver._session_http.post('/wda/deviceSwipe', data=data) # 如果找不到接口说明是低版本的wda,低于1.3版本没有此接口 except wda.WDARequestError as e: return self.driver._session_http.post('/wda/swipe', data=data) except wda.WDARequestError as e: if e.status == 110: self.driver.swipe(x1, y1, x2, y2) def keyevent(self, keyname, **kwargs): """Perform keyevent on the device. Args: keyname: home/volumeUp/volumeDown **kwargs: """ try: keyname = KEY_EVENTS[keyname.lower()] except KeyError: raise ValueError("Invalid name: %s, should be one of ('home', 'volumeUp', 'volumeDown')" % keyname) else: self.press(keyname) def press(self, keys): """Some keys in ["home", "volumeUp", "volumeDown"] can be pressed. """ self.driver.press(keys) def text(self, text, enter=True): """Input text on the device. Args: text: text to input enter: True if you need to enter a newline at the end Examples: >>> text("test") >>> text("中文") """ if enter: text += '\n' self.driver.send_keys(text) def install_app(self, file_or_url, **kwargs): """ curl -X POST $JSON_HEADER \ -d "{\"desiredCapabilities\":{\"bundleId\":\"com.apple.mobilesafari\", \"app\":\"[host_path]/magicapp.app\"}}" \ $DEVICE_URL/session https://github.com/facebook/WebDriverAgent/wiki/Queries Install app from the device. Args: file_or_url: file or url to install Returns: bundle ID Raises: LocalDeviceError: If the device is remote. """ if not self.is_local_device: raise LocalDeviceError() return TIDevice.install_app(self.udid, file_or_url) def uninstall_app(self, bundle_id): """Uninstall app from the device. Notes: It seems always return True. Args: bundle_id: the app bundle id, e.g ``com.apple.mobilesafari`` Raises: LocalDeviceError: If the device is remote. """ if not self.is_local_device: raise LocalDeviceError() return TIDevice.uninstall_app(self.udid, bundle_id) def start_app(self, bundle_id, *args, **kwargs): """ Args: bundle_id: the app bundle id, e.g ``com.apple.mobilesafari`` Returns: Process ID. Examples: >>> start_app('com.apple.mobilesafari') """ if not self.is_local_device: # Note: If the bundle_id does not exist, it may get stuck. try: return self.driver.app_launch(bundle_id) except requests.exceptions.ReadTimeout: raise AirtestError(f"App launch timeout, please check if the app is installed: {bundle_id}") else: return TIDevice.start_app(self.udid, bundle_id) def stop_app(self, bundle_id): """ Note: Both ways of killing the app may fail, nothing responds or just closes the app to the background instead of actually killing it and no error will be reported. """ try: if not self.is_local_device: raise LocalDeviceError() TIDevice.stop_app(self.udid, bundle_id) except: pass finally: self.driver.app_stop(bundle_id=bundle_id) def list_app(self, type="user"): """ Returns a list of installed applications on the device. Args: type (str, optional): The type of applications to list. Defaults to "user". Possible values are "user", "system", or "all". Returns: list: A list of tuples containing the bundle ID, display name, and version of the installed applications. e.g. [('com.apple.mobilesafari', 'Safari', '8.0'), ...] Raises: LocalDeviceError: If the device is remote. """ if not self.is_local_device: raise LocalDeviceError() return TIDevice.list_app(self.udid, app_type=type) def app_state(self, bundle_id): """ Get app state and ruturn. Args: bundle_id: Bundle ID of app. Returns: { "value": 4, "sessionId": "0363BDC5-4335-47ED-A54E-F7CCB65C6A65" } Value 1(not running) 2(running in background) 3(running in foreground)? 4(running). """ return self.driver.app_state(bundle_id=bundle_id) def app_current(self): """Get the app current. Notes: Might not work on all devices. Returns: Current app state dict, eg: {"pid": 1281, "name": "", "bundleId": "com.netease.cloudmusic"} """ return self.driver.app_current() def get_clipboard(self, wda_bundle_id=None, *args, **kwargs): """Get clipboard text. Before calling the WDA interface, you need to ensure that WDA was foreground. If there are multiple WDA on your device, please specify the active WDA by parameter wda_bundle_id. Args: wda_bundle_id: The bundle id of the running WDA, if None, will use default WDA bundle id. Returns: Clipboard text. Raises: LocalDeviceError: If the device is remote and the wda_bundle_id parameter is not provided. Notes: If you want to use this function, you have to set WDA foreground which would switch the current screen of the phone. Then we will try to switch back to the screen before. """ if wda_bundle_id is None: if not self.is_local_device: raise LocalDeviceError("Remote device need to set running wda bundle id parameter, \ e.g. get_clipboard('wda_bundle_id').") wda_bundle_id = self.wda_bundle_id # Set wda foreground, it's necessary. try: current_app_bundle_id = self.app_current().get("bundleId", None) except: current_app_bundle_id = None try: self.driver.app_launch(wda_bundle_id) except: pass # 某些机型版本下,有一定概率获取失败,尝试重试一次 clipboard_text = self.driver._session_http.post("/wda/getPasteboard").value if not clipboard_text: clipboard_text = self.driver._session_http.post("/wda/getPasteboard").value decoded_text = base64.b64decode(clipboard_text).decode('utf-8') # Switch back to the screen before. if current_app_bundle_id: self.driver.app_launch(current_app_bundle_id) else: LOGGING.warning("we can't switch back to the app before, because can't get bundle id.") return decoded_text def set_clipboard(self, content, wda_bundle_id=None, *args, **kwargs): """ Set the clipboard content on the device. Args: content (str): The content to be set on the clipboard. wda_bundle_id (str, optional): The bundle ID of the WDA app. Defaults to None. Raises: LocalDeviceError: If the device is remote and the wda_bundle_id parameter is not provided. Returns: None """ if wda_bundle_id is None: if not self.is_local_device: raise LocalDeviceError("Remote device need to set running wda bundle id parameter, \ e.g. set_clipboard('content', 'wda_bundle_id').") wda_bundle_id = self.wda_bundle_id # Set wda foreground, it's necessary. try: current_app_bundle_id = self.app_current().get("bundleId", None) except: current_app_bundle_id = None try: self.driver.app_launch(wda_bundle_id) except: pass self.driver.set_clipboard(content) clipboard_text = self.driver._session_http.post("/wda/getPasteboard").value decoded_text = base64.b64decode(clipboard_text).decode('utf-8') if decoded_text != content: # 部分机型偶现设置剪切板失败,重试一次 self.driver.set_clipboard(content) # Switch back to the screen before. if current_app_bundle_id: self.driver.app_launch(current_app_bundle_id) else: LOGGING.warning("we can't switch back to the app before, because can't get bundle id.") def paste(self, wda_bundle_id=None, *args, **kwargs): """ Paste the current clipboard content on the device. Args: wda_bundle_id (str, optional): The bundle ID of the WDA app. Defaults to None. Raises: LocalDeviceError: If the device is remote and the wda_bundle_id parameter is not provided. Returns: None """ self.text(self.get_clipboard(wda_bundle_id=wda_bundle_id)) def get_ip_address(self): """Get ip address from WDA. Returns: If no IP address has been found, otherwise return the IP address. """ ios_status = self.driver.status()['ios'] # If use modified WDA, try to get real wifi IP first. return ios_status.get('wifiIP', ios_status['ip']) def device_status(self): """Show status return by WDA. Returns: Dicts of infos. """ return self.driver.status() def _touch_point_by_orientation(self, tuple_xy): """ Convert image coordinates to physical display coordinates, the arbitrary point (origin) is upper left corner of the device physical display. Args: tuple_xy: image coordinates (x, y) Returns: physical coordinates (x, y) """ x, y = tuple_xy # 1. 如果使用了2022.03.30之后发布的iOS-Tagent版本,则必须要进行竖屏坐标转换。 # 2. 如果使用了appium/WebDriverAgent>=4.1.4版本,直接使用原坐标即可,无需转换。 # 3. 如果使用了appium/WebDriverAgent<4.1.4版本,或低版本的iOS-Tagent,并且ipad下横屏点击异常,请改用airtest<=1.2.4。 if self.using_ios_tagent: width = self.display_info["width"] height = self.display_info["height"] if self.orientation in [wda.LANDSCAPE, wda.LANDSCAPE_RIGHT]: width, height = height, width if x < 1 and y < 1: x = x * width y = y * height x, y = XYTransformer.up_2_ori( (x, y), (width, height), self.orientation ) return x, y def _transform_xy(self, pos): x, y = self._touch_point_by_orientation(pos) # Scale touch postion. if not (x < 1 and y < 1): x, y = int(x * self.touch_factor), int(y * self.touch_factor) return x, y def _check_orientation_change(self): pass def is_locked(self): """ Return True or False whether the device is locked or not. Notes: Might not work on some devices. Returns: True or False. """ return self.driver.locked() def unlock(self): """Unlock the device, unlock screen, double press home. Notes: Might not work on all devices. """ return self.driver.unlock() def lock(self): """Lock the device, lock screen. Notes: Might not work on all devices. """ return self.driver.lock() def setup_forward(self, port): """ Setup port forwarding from device to host. Args: port: device port Returns: host port, device port Raises: LocalDeviceError: If the device is remote. """ return self.instruct_helper.setup_proxy(int(port)) def ps(self): """Get the process list of the device. Returns: Process list of the device. """ if not self.is_local_device: raise LocalDeviceError() return TIDevice.ps(self.udid) def alert_accept(self): """ Alert accept-Actually do click first alert button. Notes: Might not work on all devices. """ return self.driver.alert.accept() def alert_dismiss(self): """Alert dissmiss-Actually do click second alert button. Notes: Might not work on all devices. """ return self.driver.alert.dismiss() def alert_wait(self, time_counter=2): """If alert apper in time_counter second it will return True,else return False (default 20.0). Notes: Might not work on all devices. """ return self.driver.alert.wait(time_counter) def alert_buttons(self): """Get alert buttons text. Notes: Might not work on all devices. Returns: # example return: ("设置", "好") """ return self.driver.alert.buttons() def alert_exists(self): """ Get True for alert exists or False. Notes: Might not work on all devices Returns: True or False """ return self.driver.alert.exists def alert_click(self, buttons): """When Arg type is list, click the first match, raise ValueError if no match. e.g. ["设置", "信任", "安装"] Notes: Might not work on all devices. """ return self.driver.alert.click(buttons) def home_interface(self): """Get True for the device status is on home interface. Reason: Some devices can Horizontal screen on the home interface. Notes: Might not work on all devices. Returns: True or False """ try: app_current_dict = self.app_current() app_current_bundleId = app_current_dict.get('bundleId') LOGGING.info("app_current_bundleId %s", app_current_bundleId) except: return False else: if app_current_bundleId in ['com.apple.springboard']: return True return False def disconnect(self): """Disconnected mjpeg and rotation_watcher. """ if self.cap_method == CAP_METHOD.MJPEG: self.mjpegcap.teardown_stream() if self.rotation_watcher: self.rotation_watcher.teardown() def start_recording(self, max_time=1800, output=None, fps=10, snapshot_sleep=0.001, orientation=0, max_size=None, *args, **kwargs): """Start recording the device display. Args: max_time: maximum screen recording time, default is 1800 output: ouput file path fps: frames per second will record snapshot_sleep: sleep time for each snapshot. orientation: 1: portrait, 2: landscape, 0: rotation, default is 0 max_size: max size of the video frame, e.g.800, default is None. Smaller sizes lead to lower system load. Returns: save_path: path of video file Examples: Record 30 seconds of video and export to the current directory test.mp4: >>> from airtest.core.api import connect_device, sleep >>> dev = connect_device("IOS:///") >>> save_path = dev.start_recording(output="test.mp4") >>> sleep(30) >>> dev.stop_recording() >>> print(save_path) >>> # the screen is portrait >>> portrait_mp4 = dev.start_recording(output="portrait.mp4", orientation=1) # or orientation="portrait" >>> sleep(30) >>> dev.stop_recording() >>> # the screen is landscape >>> landscape_mp4 = dev.start_recording(output="landscape.mp4", orientation=2) # or orientation="landscape" You can specify max_size to limit the video's maximum width/length. Smaller video sizes result in lower CPU load. >>> dev.start_recording(output="test.mp4", max_size=800) """ if fps > 10 or fps < 1: LOGGING.warning("fps should be between 1 and 10, becuase of the recording effiency") if fps > 10: fps = 10 if fps < 1: fps = 1 if self.recorder and self.recorder.is_running(): LOGGING.warning("recording is already running, please don't call again") return None logdir = "./" if ST.LOG_DIR is not None: logdir = ST.LOG_DIR if output is None: save_path = os.path.join(logdir, "screen_%s.mp4" % (time.strftime("%Y%m%d%H%M%S", time.localtime()))) else: if os.path.isabs(output): save_path = output else: save_path = os.path.join(logdir, output) max_size = get_max_size(max_size) def get_frame(): data = self.get_frame_from_stream() frame = aircv.utils.string_2_img(data) if max_size is not None: frame = resize_by_max(frame, max_size) return frame self.recorder = ScreenRecorder( save_path, get_frame, fps=fps, snapshot_sleep=snapshot_sleep, orientation=orientation) self.recorder.stop_time = max_time self.recorder.start() LOGGING.info("start recording screen to {}".format(save_path)) return save_path def stop_recording(self, ): """ Stop recording the device display. Recoding file will be kept in the device. """ LOGGING.info("stopping recording") self.recorder.stop() return None def push(self, local_path, remote_path, bundle_id=None, timeout=None): """ Pushes a file from the local machine to the iOS device. Args: remote_path (str): The path on the iOS device where the file will be saved. local_path (str): The path of the file on the local machine. bundle_id (str, optional): The bundle identifier of the app. Defaults to None. timeout (int, optional): The timeout in seconds for the remote device operation. Defaults to None. Raises: LocalDeviceError: If the device is remote. Examples: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> dev.push("test.png", "/DCIM/test.png") >>> dev.push("test.png", "/DCIM/test_rename.png") >>> dev.push("test.key", "/Documents/", "com.apple.Keynote") # Push to the Documents directory of the Keynote app >>> dev.push("test.key", "/Documents/test.key", "com.apple.Keynote") Push file without suffix cannot be renamed, so the following code will push file to the path considered as a directory >>> dev.push("test", "/Documents/test", "com.apple.Keynote") # The pushed file will be /Documents/test >>> dev.push("test", "/Documents/test_rename", "com.apple.Keynote") # The pushed file will be /Documents/test_rename/test """ if not self.is_local_device: raise LocalDeviceError() TIDevice.push(self.udid, local_path, remote_path, bundle_id=bundle_id) def pull(self, remote_path, local_path, bundle_id=None, timeout=None): """ Pulls a file or directory from the iOS device to the local machine. Args: remote_path (str): The path of the file or directory on the iOS device. local_path (str): The path where the file or directory will be saved on the local machine. bundle_id (str, optional): The bundle identifier of the app. Defaults to None. Required for remote devices. timeout (int, optional): The timeout in seconds for the remote device operation. Defaults to None. Raises: LocalDeviceError: If the device is remote. Examples: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> dev.pull("/DCIM/test.png", "test.png") >>> dev.pull("/Documents/test.key", "test.key", "com.apple.Keynote") >>> dev.pull("/Documents/test.key", "dir/test.key", "com.apple.Keynote") >>> dev.pull("/Documents/test.key", "test_rename.key", "com.apple.Keynote") """ if not self.is_local_device: raise LocalDeviceError() TIDevice.pull(self.udid, remote_path, local_path, bundle_id=bundle_id, timeout=timeout) @logwrap def ls(self, remote_path, bundle_id=None): """ List files and directories in the specified remote path on the iOS device. Args: remote_path (str): The remote path to list. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Required for remote devices. Returns: list: A list of files and directories in the remote path. Each item in the list is a dictionary with the following keys: - 'type': The type of the item. This can be 'Directory' or 'File'. - 'size': The size of the item in bytes. - 'last_modified': The last modification time of the item, in the format 'YYYY-MM-DD HH:MM:SS'. - 'name': The name of the item, including the path relative to `remote_path`. e.g. [ {'type': 'Directory', 'size': 1024, 'last_modified': 'YYYY-MM-DD HH:MM:SS', 'name': 'example_directory/'}, {'type': 'File', 'size': 2048, 'last_modified': 'YYYY-MM-DD HH:MM:SS', 'name': 'example_file.txt'} ] Raises: LocalDeviceError: If the device is remote. Examples: List files and directories in the DCIM directory:: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> print(dev.ls("/DCIM/")) [{'type': 'Directory', 'size': 96, 'last_modified': '2021-12-01 15:30:13', 'name': '100APPLE/'}, {'type': 'Directory', 'size': 96, 'last_modified': '2021-07-20 17:29:01', 'name': '.MISC/'}] List files and directories in the Documents directory of the Keynote app:: >>> print(dev.ls("/Documents", "com.apple.Keynote")) [{'type': 'File', 'size': 302626, 'last_modified': '2024-06-25 11:25:25', 'name': 'test.key'}] """ if not self.is_local_device: raise LocalDeviceError() return TIDevice.ls(self.udid, remote_path, bundle_id=bundle_id) @logwrap def rm(self, remote_path, bundle_id=None): """ Remove a file or directory from the iOS device. Args: remote_path (str): The remote path to remove. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Raises: LocalDeviceError: If the device is remote. AirtestError: If the file or directory does not exist. Examples: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> dev.rm("/Documents/test.key", "com.apple.Keynote") >>> dev.rm("/Documents/test_dir", "com.apple.Keynote") """ if not self.is_local_device: raise LocalDeviceError() TIDevice.rm(self.udid, remote_path, bundle_id=bundle_id) @logwrap def mkdir(self, remote_path, bundle_id=None): """ Create a directory on the iOS device. Args: remote_path (str): The remote path to create. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Examples: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> dev.mkdir("/Documents/test_dir", "com.apple.Keynote") """ if not self.is_local_device: raise LocalDeviceError() TIDevice.mkdir(self.udid, remote_path, bundle_id=bundle_id) def is_dir(self, remote_path, bundle_id=None): """ Check if the specified path on the iOS device is a directory. Args: remote_path (str): The remote path to check. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Returns: bool: True if the path is a directory, False otherwise. Exapmles: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> print(dev.is_dir("/DCIM/")) True >>> print(dev.is_dir("/Documents/test.key", "com.apple.Keynote")) False """ if not self.is_local_device: raise LocalDeviceError() return TIDevice.is_dir(self.udid, remote_path, bundle_id=bundle_id)
class IOS(Device): '''IOS client. - before this you have to run `WebDriverAgent <https://github.com/AirtestProject/iOS-Tagent>`_ - ``xcodebuild -project path/to/WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination "id=$(idevice_id -l)" test`` - ``iproxy $port 8100 $udid`` ''' def __init__(self, addr=DEFAULT_ADDR, cap_method=CAP_METHOD.MJPEG, mjpeg_port=None, udid=None, name=None, serialno=None, wda_bundle_id=None): pass def _get_default_device(self): '''Get local default device when no udid. Returns: Local device udid. ''' pass def _get_default_wda_bundle_id(self): '''Get local default device's WDA bundleID when no WDA bundleID. Returns: Local device's WDA bundleID. ''' pass def _get_default_running_wda_bundle_id(self): '''Get the bundleID of the WDA that is currently running on local device. Returns: Local device's running WDA bundleID. ''' pass @property def wda_bundle_id(self): pass @property def ip(self): '''Returns the IP address of the host connected to the iOS phone. It is not the IP address of the iOS phone. If you want to get the IP address of the phone, you can access the interface `get_ip_address`. For example: when the device is connected via http://localhost:8100, return localhost. If it is a remote device http://192.168.xx.xx:8100, it returns the IP address of 192.168.xx.xx. Returns: IP. ''' pass @property def uuid(self): pass @property def using_ios_tagent(self): ''' 当前基础版本:appium/WebDriverAgent 4.1.4 基于上述版本,2022.3.30之后发布的iOS-Tagent版本,在/status接口中新增了一个Version参数,如果能检查到本参数,说明使用了新版本ios-Tagent 该版本基于Appium版的WDA做了一些改动,可以更快地进行点击和滑动,并优化了部分UI树的获取逻辑 但是所有的坐标都为竖屏坐标,需要airtest自行根据方向做转换 同时,大于4.1.4版本的appium/WebDriverAgent不再需要针对ipad进行特殊的横屏坐标处理了 Returns: True if using ios-tagent, else False. ''' pass def _fetch_new_session(self): '''Re-acquire a new session. ''' pass @property def is_pad(self): ''' Determine whether it is an ipad(or 6P/7P/8P), if it is, in the case of horizontal screen + desktop, the coordinates need to be switched to vertical screen coordinates to click correctly (WDA bug). 判断是否是ipad(或 6P/7P/8P),如果是,在横屏+桌面的情况下,坐标需要切换成竖屏坐标才能正确点击(WDA的bug) Returns: True if it is an ipad, else False. ''' pass @property def device_info(self): ''' Get the device info. Notes: Might not work on all devices. Returns: Dict for device info, e.g. AttrDict({ 'timeZone': 'GMT+0800', 'currentLocale': 'zh_CN', 'model': 'iPhone', 'uuid': '90CD6AB7-11C7-4E52-B2D3-61FA31D791EC', 'userInterfaceIdiom': 0, 'userInterfaceStyle': 'light', 'name': 'iPhone', 'isSimulator': False}) ''' pass def _register_rotation_watcher(self): ''' Register callbacks for Android and minicap when rotation of screen has changed, callback is called in another thread, so be careful about thread-safety. ''' pass def window_size(self): ''' Returns: Window size (width, height). ''' pass @property def orientation(self): ''' Returns: Device orientation status in LANDSACPE POR. ''' pass @orientation.setter def orientation(self): ''' Args: value(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT | UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN ''' pass def get_orientation(self): pass @property def display_info(self): pass def _display_info(self): pass @property def touch_factor(self): pass @touch_factor.setter def touch_factor(self): ''' Func touch_factor is used to convert click coordinates: mobile phone real coordinates = touch_factor * screen coordinates. In general, no manual settings are required. touch_factor用于换算点击坐标:手机真实坐标 = touch_factor * 屏幕坐标 默认计算方式是: self.display_info['window_height'] / self.display_info['height'] 但在部分特殊型号手机上可能不准确,例如iOS14.4的7P,默认值为 1/3,但部分7P点击位置不准确,可自行设置为:self.touch_factor = 1 / 3.3 (一般情况下,无需手动设置!) Examples: >>> device = connect_device("iOS:///") >>> device.touch((100, 100)) # wrong position >>> print(device.touch_factor) 0.333333 >>> device.touch_factor = 1 / 3.3 # default is 1/3 >>> device.touch((100, 100)) Args: factor: real_pos / pixel_pos, e.g: 1/self.driver.scale ''' pass def get_render_resolution(self): '''Return render resolution after rotation. Returns: offset_x, offset_y, offset_width and offset_height of the display. ''' pass def get_current_resolution(self): pass def home(self): pass def _neo_wda_screenshot(self): ''' This is almost same as wda implementation, but without png header check, as response data is now jpg format in mid quality. ''' pass def snapshot(self, filename=None, quality=10, max_size=None): '''Take snapshot. Args: filename: save screenshot to filename quality: The image quality, integer in range [1, 99] max_size: the maximum size of the picture, e.g 1200 Returns: Screen snapshot's cv2 object. ''' pass def get_frame_from_stream(self): pass def touch_factor(self): ''' Args: pos: coordinates (x, y), can be float(percent) or int duration (optional): tap_hold duration Returns: None(iOS may all use vertical screen coordinates, so coordinates will not be returned.) Examples: >>> touch((100, 100)) >>> touch((0.5, 0.5), duration=1) ''' pass def _quick_click(self, x, y, duration): ''' The method extended from the facebook-wda third-party library. Use modified appium wda to perform quick click. Args: x, y (int, float): float(percent), int(coordicate) duration (optional): tap_hold duration ''' pass def double_click(self, pos): pass def swipe(self, fpos, tpos, duration=0, delay=None, *args, **kwargs): ''' Args: fpos: start point tpos: end point duration (float): start coordinate press duration (seconds), default is None delay (float): start coordinate to end coordinate duration (seconds) Returns: None Examples: >>> swipe((1050, 1900), (150, 1900)) >>> swipe((0.2, 0.5), (0.8, 0.5)) ''' pass def ios_tagent_swipe(fpos, tpos, delay=None): pass def _quick_swipe(self, x1, y1, x2, y2, delay): ''' The method extended from the facebook-wda third-party library. Use modified appium wda to perform quick swipe. Args: x1, y1, x2, y2 (int, float): float(percent), int(coordicate) delay (float): start coordinate to end coordinate duration (seconds) ''' pass def keyevent(self, keyname, **kwargs): '''Perform keyevent on the device. Args: keyname: home/volumeUp/volumeDown **kwargs: ''' pass def press(self, keys): '''Some keys in ["home", "volumeUp", "volumeDown"] can be pressed. ''' pass def text(self, text, enter=True): '''Input text on the device. Args: text: text to input enter: True if you need to enter a newline at the end Examples: >>> text("test") >>> text("中文") ''' pass def install_app(self, file_or_url, **kwargs): ''' curl -X POST $JSON_HEADER -d "{"desiredCapabilities":{"bundleId":"com.apple.mobilesafari", "app":"[host_path]/magicapp.app"}}" $DEVICE_URL/session https://github.com/facebook/WebDriverAgent/wiki/Queries Install app from the device. Args: file_or_url: file or url to install Returns: bundle ID Raises: LocalDeviceError: If the device is remote. ''' pass def uninstall_app(self, bundle_id): '''Uninstall app from the device. Notes: It seems always return True. Args: bundle_id: the app bundle id, e.g ``com.apple.mobilesafari`` Raises: LocalDeviceError: If the device is remote. ''' pass def start_app(self, bundle_id, *args, **kwargs): ''' Args: bundle_id: the app bundle id, e.g ``com.apple.mobilesafari`` Returns: Process ID. Examples: >>> start_app('com.apple.mobilesafari') ''' pass def stop_app(self, bundle_id): ''' Note: Both ways of killing the app may fail, nothing responds or just closes the app to the background instead of actually killing it and no error will be reported. ''' pass def list_app(self, type="user"): ''' Returns a list of installed applications on the device. Args: type (str, optional): The type of applications to list. Defaults to "user". Possible values are "user", "system", or "all". Returns: list: A list of tuples containing the bundle ID, display name, and version of the installed applications. e.g. [('com.apple.mobilesafari', 'Safari', '8.0'), ...] Raises: LocalDeviceError: If the device is remote. ''' pass def app_state(self, bundle_id): ''' Get app state and ruturn. Args: bundle_id: Bundle ID of app. Returns: { "value": 4, "sessionId": "0363BDC5-4335-47ED-A54E-F7CCB65C6A65" } Value 1(not running) 2(running in background) 3(running in foreground)? 4(running). ''' pass def app_current(self): '''Get the app current. Notes: Might not work on all devices. Returns: Current app state dict, eg: {"pid": 1281, "name": "", "bundleId": "com.netease.cloudmusic"} ''' pass def get_clipboard(self, wda_bundle_id=None, *args, **kwargs): '''Get clipboard text. Before calling the WDA interface, you need to ensure that WDA was foreground. If there are multiple WDA on your device, please specify the active WDA by parameter wda_bundle_id. Args: wda_bundle_id: The bundle id of the running WDA, if None, will use default WDA bundle id. Returns: Clipboard text. Raises: LocalDeviceError: If the device is remote and the wda_bundle_id parameter is not provided. Notes: If you want to use this function, you have to set WDA foreground which would switch the current screen of the phone. Then we will try to switch back to the screen before. ''' pass def set_clipboard(self, content, wda_bundle_id=None, *args, **kwargs): ''' Set the clipboard content on the device. Args: content (str): The content to be set on the clipboard. wda_bundle_id (str, optional): The bundle ID of the WDA app. Defaults to None. Raises: LocalDeviceError: If the device is remote and the wda_bundle_id parameter is not provided. Returns: None ''' pass def paste(self, wda_bundle_id=None, *args, **kwargs): ''' Paste the current clipboard content on the device. Args: wda_bundle_id (str, optional): The bundle ID of the WDA app. Defaults to None. Raises: LocalDeviceError: If the device is remote and the wda_bundle_id parameter is not provided. Returns: None ''' pass def get_ip_address(self): '''Get ip address from WDA. Returns: If no IP address has been found, otherwise return the IP address. ''' pass def device_status(self): '''Show status return by WDA. Returns: Dicts of infos. ''' pass def _touch_point_by_orientation(self, tuple_xy): ''' Convert image coordinates to physical display coordinates, the arbitrary point (origin) is upper left corner of the device physical display. Args: tuple_xy: image coordinates (x, y) Returns: physical coordinates (x, y) ''' pass def _transform_xy(self, pos): pass def _check_orientation_change(self): pass def is_locked(self): ''' Return True or False whether the device is locked or not. Notes: Might not work on some devices. Returns: True or False. ''' pass def unlock(self): '''Unlock the device, unlock screen, double press home. Notes: Might not work on all devices. ''' pass def lock(self): '''Lock the device, lock screen. Notes: Might not work on all devices. ''' pass def setup_forward(self, port): ''' Setup port forwarding from device to host. Args: port: device port Returns: host port, device port Raises: LocalDeviceError: If the device is remote. ''' pass def ps(self): '''Get the process list of the device. Returns: Process list of the device. ''' pass def alert_accept(self): ''' Alert accept-Actually do click first alert button. Notes: Might not work on all devices. ''' pass def alert_dismiss(self): '''Alert dissmiss-Actually do click second alert button. Notes: Might not work on all devices. ''' pass def alert_wait(self, time_counter=2): '''If alert apper in time_counter second it will return True,else return False (default 20.0). Notes: Might not work on all devices. ''' pass def alert_buttons(self): '''Get alert buttons text. Notes: Might not work on all devices. Returns: # example return: ("设置", "好") ''' pass def alert_exists(self): ''' Get True for alert exists or False. Notes: Might not work on all devices Returns: True or False ''' pass def alert_click(self, buttons): '''When Arg type is list, click the first match, raise ValueError if no match. e.g. ["设置", "信任", "安装"] Notes: Might not work on all devices. ''' pass def home_interface(self): '''Get True for the device status is on home interface. Reason: Some devices can Horizontal screen on the home interface. Notes: Might not work on all devices. Returns: True or False ''' pass def disconnect(self): '''Disconnected mjpeg and rotation_watcher. ''' pass def start_recording(self, max_time=1800, output=None, fps=10, snapshot_sleep=0.001, orientation=0, max_size=None, *args, **kwargs): '''Start recording the device display. Args: max_time: maximum screen recording time, default is 1800 output: ouput file path fps: frames per second will record snapshot_sleep: sleep time for each snapshot. orientation: 1: portrait, 2: landscape, 0: rotation, default is 0 max_size: max size of the video frame, e.g.800, default is None. Smaller sizes lead to lower system load. Returns: save_path: path of video file Examples: Record 30 seconds of video and export to the current directory test.mp4: >>> from airtest.core.api import connect_device, sleep >>> dev = connect_device("IOS:///") >>> save_path = dev.start_recording(output="test.mp4") >>> sleep(30) >>> dev.stop_recording() >>> print(save_path) >>> # the screen is portrait >>> portrait_mp4 = dev.start_recording(output="portrait.mp4", orientation=1) # or orientation="portrait" >>> sleep(30) >>> dev.stop_recording() >>> # the screen is landscape >>> landscape_mp4 = dev.start_recording(output="landscape.mp4", orientation=2) # or orientation="landscape" You can specify max_size to limit the video's maximum width/length. Smaller video sizes result in lower CPU load. >>> dev.start_recording(output="test.mp4", max_size=800) ''' pass def get_frame_from_stream(self): pass def stop_recording(self, ): ''' Stop recording the device display. Recoding file will be kept in the device. ''' pass def push(self, local_path, remote_path, bundle_id=None, timeout=None): ''' Pushes a file from the local machine to the iOS device. Args: remote_path (str): The path on the iOS device where the file will be saved. local_path (str): The path of the file on the local machine. bundle_id (str, optional): The bundle identifier of the app. Defaults to None. timeout (int, optional): The timeout in seconds for the remote device operation. Defaults to None. Raises: LocalDeviceError: If the device is remote. Examples: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> dev.push("test.png", "/DCIM/test.png") >>> dev.push("test.png", "/DCIM/test_rename.png") >>> dev.push("test.key", "/Documents/", "com.apple.Keynote") # Push to the Documents directory of the Keynote app >>> dev.push("test.key", "/Documents/test.key", "com.apple.Keynote") Push file without suffix cannot be renamed, so the following code will push file to the path considered as a directory >>> dev.push("test", "/Documents/test", "com.apple.Keynote") # The pushed file will be /Documents/test >>> dev.push("test", "/Documents/test_rename", "com.apple.Keynote") # The pushed file will be /Documents/test_rename/test ''' pass def pull(self, remote_path, local_path, bundle_id=None, timeout=None): ''' Pulls a file or directory from the iOS device to the local machine. Args: remote_path (str): The path of the file or directory on the iOS device. local_path (str): The path where the file or directory will be saved on the local machine. bundle_id (str, optional): The bundle identifier of the app. Defaults to None. Required for remote devices. timeout (int, optional): The timeout in seconds for the remote device operation. Defaults to None. Raises: LocalDeviceError: If the device is remote. Examples: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> dev.pull("/DCIM/test.png", "test.png") >>> dev.pull("/Documents/test.key", "test.key", "com.apple.Keynote") >>> dev.pull("/Documents/test.key", "dir/test.key", "com.apple.Keynote") >>> dev.pull("/Documents/test.key", "test_rename.key", "com.apple.Keynote") ''' pass @logwrap def ls(self, remote_path, bundle_id=None): ''' List files and directories in the specified remote path on the iOS device. Args: remote_path (str): The remote path to list. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Required for remote devices. Returns: list: A list of files and directories in the remote path. Each item in the list is a dictionary with the following keys: - 'type': The type of the item. This can be 'Directory' or 'File'. - 'size': The size of the item in bytes. - 'last_modified': The last modification time of the item, in the format 'YYYY-MM-DD HH:MM:SS'. - 'name': The name of the item, including the path relative to `remote_path`. e.g. [ {'type': 'Directory', 'size': 1024, 'last_modified': 'YYYY-MM-DD HH:MM:SS', 'name': 'example_directory/'}, {'type': 'File', 'size': 2048, 'last_modified': 'YYYY-MM-DD HH:MM:SS', 'name': 'example_file.txt'} ] Raises: LocalDeviceError: If the device is remote. Examples: List files and directories in the DCIM directory:: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> print(dev.ls("/DCIM/")) [{'type': 'Directory', 'size': 96, 'last_modified': '2021-12-01 15:30:13', 'name': '100APPLE/'}, {'type': 'Directory', 'size': 96, 'last_modified': '2021-07-20 17:29:01', 'name': '.MISC/'}] List files and directories in the Documents directory of the Keynote app:: >>> print(dev.ls("/Documents", "com.apple.Keynote")) [{'type': 'File', 'size': 302626, 'last_modified': '2024-06-25 11:25:25', 'name': 'test.key'}] ''' pass @logwrap def rm(self, remote_path, bundle_id=None): ''' Remove a file or directory from the iOS device. Args: remote_path (str): The remote path to remove. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Raises: LocalDeviceError: If the device is remote. AirtestError: If the file or directory does not exist. Examples: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> dev.rm("/Documents/test.key", "com.apple.Keynote") >>> dev.rm("/Documents/test_dir", "com.apple.Keynote") ''' pass @logwrap def mkdir(self, remote_path, bundle_id=None): ''' Create a directory on the iOS device. Args: remote_path (str): The remote path to create. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Examples: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> dev.mkdir("/Documents/test_dir", "com.apple.Keynote") ''' pass def is_dir(self, remote_path, bundle_id=None): ''' Check if the specified path on the iOS device is a directory. Args: remote_path (str): The remote path to check. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Returns: bool: True if the path is a directory, False otherwise. Exapmles: >>> dev = connect_device("iOS:///http+usbmux://udid") >>> print(dev.is_dir("/DCIM/")) True >>> print(dev.is_dir("/Documents/test.key", "com.apple.Keynote")) False ''' pass
87
58
16
2
7
7
2
1.07
1
21
12
0
70
21
70
94
1,222
223
482
159
393
517
438
140
365
8
2
4
162
3,395
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_yosemite.py
tests.test_yosemite.TestYosemiteExt
class TestYosemiteExt(unittest.TestCase): @classmethod def setUpClass(cls): cls.adb = ADB() devices = cls.adb.devices() if not devices: raise RuntimeError("At lease one adb device required") cls.adb.serialno = devices[0][0] cls.yosemite = YosemiteExt(cls.adb) def test_change_lang(self): self.yosemite.change_lang("ja") self.yosemite.change_lang("zh") def test_clipboard(self): text1 = "test clipboard" self.yosemite.set_clipboard(text1) self.assertEqual(self.yosemite.get_clipboard(), text1) # test escape special char text2 = "test clipboard with $pecial char #@!#%$#^&*()'" self.yosemite.set_clipboard(text2) self.assertEqual(self.yosemite.get_clipboard(), text2)
class TestYosemiteExt(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_change_lang(self): pass def test_clipboard(self): pass
5
0
6
0
6
1
1
0.11
1
3
2
0
2
0
3
75
24
4
19
8
14
2
18
7
14
2
2
1
4
3,396
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/constant.py
airtest.core.ios.constant.TOUCH_METHOD
class TOUCH_METHOD(object): WDATOUCH = "WDATOUCH"
class TOUCH_METHOD(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
3,397
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_yosemite.py
tests.test_yosemite.TestJavacap
class TestJavacap(unittest.TestCase): @classmethod def setUpClass(cls): cls.adb = ADB() devices = cls.adb.devices() if not devices: raise RuntimeError("At lease one adb device required") cls.adb.serialno = devices[0][0] cls.javacap = Javacap(cls.adb) def test_0_get_frame(self): frame = self.javacap.get_frame_from_stream() frame = string_2_img(frame) self.assertIsInstance(frame, ndarray) def test_snapshot(self): img = self.javacap.snapshot() self.assertIsInstance(img, ndarray) def test_teardown(self): self.javacap.get_frame_from_stream() self.javacap.teardown_stream() @classmethod def tearDownClass(cls): cls.javacap.teardown_stream()
class TestJavacap(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_0_get_frame(self): pass def test_snapshot(self): pass def test_teardown(self): pass @classmethod def tearDownClass(cls): pass
8
0
4
0
4
0
1
0
1
3
2
0
3
0
5
77
27
5
22
11
14
0
20
9
14
2
2
1
6
3,398
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/linux/linux.py
airtest.core.linux.linux.Linux
class Linux(Device): """Linux desktop.""" def __init__(self, pid=None, **kwargs): self.pid = None self._focus_rect = (0, 0, 0, 0) self.mouse = mouse self.keyboard = keyboard def shell(self, cmd): """ Run shell command in subprocess Args: cmd: command to be run Raises: subprocess.CalledProcessError: when command returns non-zero exit status Returns: command output as a byte string """ return subprocess.check_output(cmd, shell=True) def snapshot(self, filename="tmp.png", quality=None): """ Take a screenshot and save it to `tmp.png` filename by default Args: filename: name of file where to store the screenshot quality: ignored Returns: display the screenshot """ w, h = self.get_current_resolution() dsp = display.Display() root = dsp.screen().root raw = root.get_image(0, 0, w, h, X.ZPixmap, 0xffffffff) image = Image.frombytes("RGB", (w, h), raw.data, "raw", "BGRX") from airtest.aircv.utils import pil_2_cv2 image = pil_2_cv2(image) return image def keyevent(self, keyname, **kwargs): """ Perform a key event References: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html Args: keyname: key event **kwargs: optional arguments Returns: None """ self.keyboard.SendKeys(keyname) def text(self, text, **kwargs): """ Input text Args: text: text to input **kwargs: optional arguments Returns: None """ self.keyevent(text) def touch(self, pos, **kwargs): """ Perform mouse click action References: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.mouse.html Args: pos: coordinates where to click **kwargs: optional arguments Returns: None """ duration = kwargs.get("duration", 0.01) right_click = kwargs.get("right_click", False) button = "right" if right_click else "left" self.mouse.press(button=button, coords=pos) time.sleep(duration) self.mouse.release(button=button, coords=pos) def double_click(self, pos): self.mouse.double_click(coords=pos) def swipe(self, p1, p2, duration=0.8, steps=5): """ Perform swipe (mouse press and mouse release) Args: p1: start point p2: end point duration: time interval to perform the swipe action steps: size of the swipe step Returns: None """ from_x, from_y = p1 to_x, to_y = p2 interval = float(duration) / (steps + 1) self.mouse.press(coords=(from_x, from_y)) time.sleep(interval) for i in range(1, steps): self.mouse.move(coords=( int(from_x + (to_x - from_x) * i / steps), int(from_y + (to_y - from_y) * i / steps), )) time.sleep(interval) for i in range(10): self.mouse.move(coords=(to_x, to_y)) time.sleep(interval) self.mouse.release(coords=(to_x, to_y)) def start_app(self, path, *args, **kwargs): """ Start the application Args: path: full path to the application Returns: None """ super(Linux, self).start_app(path) def stop_app(self, pid): """ Stop the application Args: pid: process ID of the application to be stopped Returns: None """ super(Linux, self).stop_app(pid) def get_current_resolution(self): d = display.Display() screen = d.screen() w, h = (screen["width_in_pixels"], screen["height_in_pixels"]) return w, h def get_ip_address(self): """ Return default external ip address of the linux os. Returns: :py:obj:`str`: ip address """ return socket.gethostbyname(socket.gethostname())
class Linux(Device): '''Linux desktop.''' def __init__(self, pid=None, **kwargs): pass def shell(self, cmd): ''' Run shell command in subprocess Args: cmd: command to be run Raises: subprocess.CalledProcessError: when command returns non-zero exit status Returns: command output as a byte string ''' pass def snapshot(self, filename="tmp.png", quality=None): ''' Take a screenshot and save it to `tmp.png` filename by default Args: filename: name of file where to store the screenshot quality: ignored Returns: display the screenshot ''' pass def keyevent(self, keyname, **kwargs): ''' Perform a key event References: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html Args: keyname: key event **kwargs: optional arguments Returns: None ''' pass def text(self, text, **kwargs): ''' Input text Args: text: text to input **kwargs: optional arguments Returns: None ''' pass def touch(self, pos, **kwargs): ''' Perform mouse click action References: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.mouse.html Args: pos: coordinates where to click **kwargs: optional arguments Returns: None ''' pass def double_click(self, pos): pass def swipe(self, p1, p2, duration=0.8, steps=5): ''' Perform swipe (mouse press and mouse release) Args: p1: start point p2: end point duration: time interval to perform the swipe action steps: size of the swipe step Returns: None ''' pass def start_app(self, path, *args, **kwargs): ''' Start the application Args: path: full path to the application Returns: None ''' pass def stop_app(self, pid): ''' Stop the application Args: pid: process ID of the application to be stopped Returns: None ''' pass def get_current_resolution(self): pass def get_ip_address(self): ''' Return default external ip address of the linux os. Returns: :py:obj:`str`: ip address ''' pass
13
10
13
2
5
6
1
1.32
1
4
0
0
12
4
12
36
173
41
57
33
43
75
54
33
40
3
2
1
15
3,399
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_win.py
tests.test_win.TestWin
class TestWin(unittest.TestCase): @classmethod def setUpClass(cls): cls.windows = Windows() def test_shell(self): result=self.windows.shell("dir").decode('utf-8', 'ignore') self.assertIn(".", result) self.assertIn("..", result) def test_snapshot(self): try_remove(SNAPSHOT) result = self.windows.snapshot(filename=SNAPSHOT) self.assertIsInstance(result, numpy.ndarray) try_remove(SNAPSHOT) def test_keyevent(self): self.windows.keyevent("abc{ENTER}") def test_text(self): self.windows.text("abc") def test_touch(self): self.windows.touch((100, 100)) self.windows.touch((0.5, 0.5)) def test_double_click(self): self.windows.double_click((100, 100)) def test_swipe(self): self.windows.swipe((100, 100), (500, 500)) self.windows.swipe((0.1, 0.1), (0.5, 0.5)) def test_key_press_and_key_release(self): self.windows.key_press('L') self.windows.key_release('L') self.windows.key_press('S') self.windows.key_release('S') self.windows.key_press('ENTER') self.windows.key_release('ENTER') def test_mouse_move(self): self.windows.mouse_move((100, 100)) self.assertTupleEqual(win32api.GetCursorPos(), (100, 100)) self.windows.mouse_move((150, 50)) self.assertTupleEqual(win32api.GetCursorPos(), (150, 50)) def test_mouse_down_and_mouse_up(self): self.windows.mouse_down('left') self.windows.mouse_up('left') self.windows.mouse_down('middle') self.windows.mouse_up('middle') self.windows.mouse_down('right') self.windows.mouse_up('right') self.windows.mouse_down() self.windows.mouse_up() def test_record(self): self.windows.start_recording(output="test_10s.mp4") time.sleep(10+4) self.windows.stop_recording() time.sleep(2) self.assertEqual(os.path.exists("test_10s.mp4"), True) duration = 0 cap = cv2.VideoCapture("test_10s.mp4") if cap.isOpened(): rate = cap.get(5) frame_num = cap.get(7) duration = frame_num/rate self.assertEqual(duration >= 10, True) def test_clipboard(self): self.windows.set_clipboard("test") self.assertEqual(self.windows.get_clipboard(), "test") for i in range(10): text = "test clipboard with中文 $pecial char #@!#%$#^&*()'" + str(i) self.windows.set_clipboard(text) self.assertEqual(self.windows.get_clipboard(), text) time.sleep(0.5) @classmethod def tearDownClass(cls): try_remove('test_10s.mp4') try_remove('test_cv_10s.mp4')
class TestWin(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_shell(self): pass def test_snapshot(self): pass def test_keyevent(self): pass def test_text(self): pass def test_touch(self): pass def test_double_click(self): pass def test_swipe(self): pass def test_key_press_and_key_release(self): pass def test_mouse_move(self): pass def test_mouse_down_and_mouse_up(self): pass def test_record(self): pass def test_clipboard(self): pass @classmethod def tearDownClass(cls): pass
17
0
5
0
5
0
1
0.01
1
3
1
0
12
0
14
86
87
16
71
25
54
1
69
23
54
2
2
1
16