-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontacts.py
More file actions
711 lines (634 loc) · 18.9 KB
/
contacts.py
File metadata and controls
711 lines (634 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# -*- coding: utf-8 -*-
#Author: Jason Hou
#Date: 2013/06/24
############################ CHANGE HISTORY ############################
# VERSION : 1.2 Twelveth Release 27-Jun-13 Jason Hou
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. fix bug cannot slide to left or right in list view
# 2. update scroll() method to support touching highlight item
# VERSION : 1.1 Eleventh Release 26-Jun-13 Jason Hou
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. new add meun() and scroll() method
# VERSION : 1.0 Tenth Release 25-Jun-13 Jason Hou
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. update slide() method to support sliding in specified view
# VERSION : 0.9 Ninth Release 25-Jun-13 Jason Hou
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. new add favor() method
# VERSION : 0.8 Seventh Release 24-Jun-13 Glen Fan
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. new add goEditExistContact(), slideByView(), editCompany(),\
# editAnotherField(),editDetails() method
# VERSION : 0.7 Seventh Release 24-Jun-13 Faure Zhang
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. new add delete() method
# 2. rewrite getCounter() method
# VERSION : 0.6 Sixth Release 24-Jun-13 Donner Li
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. new add search(), sortAndViewAs() method
# VERSION : 0.5 Fiveth Release 24-Jun-13 Jason Hou
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. rewrite goEdit() method
# 2. fix 'Content is not allowed in prolog' bug
# VERSION : 0.4 Fourth Release 21-Jun-13 Jason Hou
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. fix the bug in wipe() method;
# 2. update the start(), goEdit(), snapshot() method;
# 3. extend getView() method to support findViewWithAttributeThatMatches();
# 4. new add isEmpty(), getCounter() method;
# 5. new add addContact() method demo
#
# VERSION : 0.3 Third Release 20-Jun-13 Jason Hou
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. add more trace info
# 2. update getView method, add 'dump' parameter
# 3. update goEdit method and return current contacts counter
# 4. new add stop, slide, goList and wipe method
# VERSION : 0.2 Second Release 18-Jun-13 Jason Hou
# REASON : Update implementation
# REFERENCE :
# DESCRIPTION : 1. add change history and function document string
# 2. update getView(), isReady() method
# 3. update the isEmpty() to goEdit() to avoid the misunderstanding
# 4. new add back, check method
# VERSION : 0.1 First Release 16-Jun-13 Jason Hou
# REASON : First implementation
# REFERENCE :
# DESCRIPTION : 1. Create the basic contacts module framework
# 2. encapsulate the findView method using method getView()
############################ CHANGE HISTORY ############################
__version__ = '1.2'
import os,sys,re
try:
for p in os.environ['PYTHONPATH'].split(';'):
if not p in sys.path:
sys.path.append(p)
except:
pass
from com.android.monkeyrunner import MonkeyRunner,MonkeyDevice,MonkeyImage
from com.dtmilano.android.viewclient import ViewClient
from log import trace
logPath = r'C:\Users\cnindoli\Desktop'
logName = 'case_log.txt'
logFile = logPath + '\\' + logName
trace = trace(logFile).trace
package = 'com.android.contacts'
activity = '.activities.PeopleActivity'
componentName = package + '/' + activity
def sleep(duration = 1):
'''
Monkey sleep
@type duration: int
@param duration: how long to sleep
'''
MonkeyRunner.sleep(duration)
class contacts:
'''
contacts class
'''
def __init__(self, device, devID='emulator-5554',sample = False):
'''
constructor
@type device: MonkeyDevice
@param device: The device or emulator connected
@type devID: str
@param serialno: the serial number of the device or emulator to connect to
@type sample: boolean
@param sample: whether take snapshot as an sampling
'''
self.device=device
self.sample=sample
self.contactCounter=0
self.startStatus=False
'''the status which indicate whether the contacts activity is started'''
#use below code to remove the status bar from the snapshot
width = int(device.getProperty('display.width'))
height = int(device.getProperty('display.height'))
density = device.getProperty('display.density')
if density == .75:
statusBarHeight = 19
elif density == 1.5:
statusBarHeight = 38
elif density == 2.0:
statusBarHeight = 50
else:
statusBarHeight = 25
self.snap_rect = 0, statusBarHeight, width, height - statusBarHeight
#define the point coordinate used to slide screen
self.left = (width/4, height/2)
self.right = (width/4*3, height/2)
self.up = (width/2, height/4)
self.down = (width/2, height/4*3)
self.center = (width/2, height/2)
trace('before instance')
self.vc=ViewClient(device, devID)
trace('after instance')
def start(self):
'''
start the contacts activity and set the startStatus True if contacts is ready.
'''
trace('Starting activity ...')
self.device.startActivity(component=componentName)
sleep(2)
self.startStatus = self.goList()
trace('Contacts is started, checking the contacts status...')
self.isReady()
sleep(2)
def stop(self):
'''
stop the contacts activity and set the startStatus False
'''
self.device.shell('am force-stop %s' % package)
trace('force stop contacts package %s' % package)
self.startStatus = False
def menu(self):
'''
press menu
'''
self.device.press('KEYCODE_MENU','DOWN_AND_UP')
trace('press menu')
def scroll(self,down=True,times=1):
'''
scoll up or down for some times then touch the highlight submenu item
@type down: boolead
@param down: scroll down if True or scroll up
@type times: int
@param times: how many times to scroll
'''
keycode = 'KEYCODE_DPAD_DOWN' if down else 'KEYCODE_DPAD_UP'
for i in range(times):
self.device.press(keycode,'DOWN_AND_UP')
trace('scroll %s' % str)
self.device.press('KEYCODE_ENTER','DOWN_AND_UP')
def back(self):
'''
press back
'''
self.device.press('KEYCODE_BACK','DOWN_AND_UP')
trace('press back')
def slide(self,str,view=None):
'''
slide the screen
@type: str
@param: 'left','right','up','down'
@type view:
@param view: specify the view, default to None
'''
if str not in ['left','right','up','down']:
raise SyntaxError("wrong parameter: choose from 'left','right','up' or 'down'")
try:
cX,cY = view.getCenter()
width = view.getWidth()
height = view.getHeight()
cL = cX - width/4, cY
cR = cX + width/4, cY
cU = cX, cY - height/4
cD = cX, cY + height/4
except AttributeError:
pass
(left, right, up, down) = (cL, cR, cU, cD) if view else (self.left, self.right, self.up, self.down)
nav = {
'left':{'start':right,'end':left},
'right':{'start':left,'end':right},
'up':{'start':down,'end':up},
'down':{'start':up,'end':down}
}
self.device.drag(nav[str]['start'], nav[str]['end'], 0.1, 10)
trace('slide the screen from %s to %s ' % (nav[str]['start'],nav[str]['end']))
sleep(2)
def getView(self,str,cD=False,iD=False,dump=True,regex=False):
'''
get the view with the specified text, content description or viewId
@type str: str
@param str: the query string
@type cD: boolean
@param cD: whether handle the query str as content description
@type iD: boolean
@param iD: whether handle the query str as viewId
@type dump: boolean
@param dump: whether execute dump before findView, depending on whether the screen is changed
@return: the view found
'''
if dump:
trace('before dump')
self.vc.dump()
trace('after dump')
if cD:
view=self.vc.findViewWithContentDescription(str)
trace('Query view with content description: %s, return is %s' % (str, view is not None))
return view
elif iD:
view=self.vc.findViewById(str)
trace('Query view by id: %s, return is %s' % (str, view is not None))
return view
elif regex:
view=self.vc.findViewWithAttributeThatMatches('text',re.compile(str))
trace('Query view that match attribute: %s, return is %s' % (str, view is not None))
return view
else:
view=self.vc.findViewWithText(str)
trace('Query view with text: %s, return is %s ' % (str, view is not None))
return view
def isReady(self):
'''
check whether the contacts is ready.
@return: True
'''
while True:
view=self.getView('Contacts list is being updated to reflect the change of language.')
if not view:
trace('Contacts is ready')
break
else:
trace('Contacts is not ready, please wait!')
sleep(2)
return True
def isEmpty(self):
'''
check whether the contacts is empty
@return: True or False
'''
self.check()
view=self.getView('No contacts.')
if view:
trace('Contacts list is empty')
return True
else:
trace('Contacts list is not empty')
return False
def getCounter(self):
'''
get the contacts counter
@return: the current contacts counter
'''
self.goList()
if self.isEmpty():
self.contactCounter=0
else:
while not self.getView('\d+ contacts?',regex=True):
self.slide('down')
sleep(3)
self.contactCounter = int(self.getView('\d+ contacts?',regex=True,dump=False).getText().split()[0])
trace('current contacts counter is %d' % self.contactCounter)
return self.contactCounter
def goList(self):
'''
check whether the screen is in contacts list view, if not, go list view via pressing back key
@return: True
'''
while True:
view=self.getView("All contacts",cD=True)
if not view:
self.back()
sleep(3)
else:
if not view.isSelected():
trace('Touch "All contacts"')
view.touch()
break
trace('Goto contacts list view')
return True
def goEdit(self):
'''
check whether the contacts is empty, then select adding and go to edit view.
@return: True
'''
self.check()
try:
self.getView('Add Contact',cD=True,dump=False).touch()
trace('Touch "Add Contact"')
sleep(5)
return True
except AttributeError: pass
try:
self.getView('Create a new contact',dump=False).touch()
trace('Touch "Create a new contact"')
sleep(5)
self.getView('Keep local').touch()
trace('Select "Keep local"')
sleep(5)
return True
except AttributeError: pass
def check(self):
'''
check whether the contacts is started before other operation about contacts
@return: True
'''
if not self.startStatus:
trace("Wrong code! please start contacts firstly in you code")
raise SyntaxError('contacts should be start firstly!')
return True
def snapshot(self,title):
'''
take snapshot
@type title: str
@param title: specify the title of snapshot
@return: snapshot object
'''
snapName = title + '.png'
snapFolder = 'snapshot'
os.system('if not exist %s\\%s mkdir %s\\%s' % (logPath, snapFolder, logPath, snapFolder))
snapFile = logPath + '\\' + snapFolder + '\\' + snapName
result = self.device.takeSnapshot().getSubImage(self.snap_rect)
trace('take snapshot without the statusbar')
result.writeToFile(snapFile,'png')
trace('save the snapshot to file: %s ' % snapFile)
return result
def wipe(self,view):
'''
wipe the text in specified view
'''
try:
self.device.drag(view.getXY(),view.getXY(),1,1)
trace('wipe text: %s' % str(view.getText()))
self.device.press('KEYCODE_DEL','DOWN_AND_UP')
except:
Exception('wipe failed')
def addContact(self,name='',phone='',email='',address=''):
self.goEdit()
try:
offset = 0
if name:
view=self.getView('id/no_id/27',iD=True)
trace('type %s' % name)
view.type(name)
view.touch()
if phone:
view=self.getView('id/no_id/46',iD=True,dump=False)
trace('type %s' % phone)
view.type(phone)
offset += 4
sleep(2)
if email:
view=self.getView('id/no_id/' + str(57 + offset), iD=True)
trace('type %s' % email)
view.type(email)
offset += 4
sleep(2)
if address:
view=self.getView('id/no_id/' + str(68 + offset), iD=True)
trace('type %s' % address)
view.type(address)
sleep(2)
view=self.getView('Done',dump=False)
view.touch()
trace('Touch Done')
finally:
sleep(5)
self.goList()
def goEditExistContact(self,str):
trace('Search a contact to edit')
view=self.search(str)
if not view:
raise SyntaxError('No '+str+' contact to edit')
view.touch()
sleep(4)
self.device.press('KEYCODE_MENU')
sleep(2)
self.device.press('KEYCODE_DPAD_DOWN')
sleep(1)
self.device.press('KEYCODE_ENTER')
sleep(3)
def editCompany(self,company,action):
view=self.getView('Add organization')
if view:
trace('Step: add a organization info')
view.touch()
sleep(1)
trace('add the company info')
self.device.type(company)
sleep(1)
view=self.getView('Title')
trace("add a company's Title")
view.type(company)
else:
trace('Step: Edit the organization info')
view=self.getView('id/no_id/42',iD=True)
self.wipe(view)
trace('Edit the company info')
self.device.type(company)
view=self.getView('id/no_id/43',iD=True)
trace("Edit the company's Title")
self.wipe(view)
self.device.type(company)
def editAnotherField(self,fieldName,content,action):
find=1
view=self.getView(fieldName)
view2=self.getView('Add another field')
while not view:
self.device.drag((440,760),(440,160),2,5)
sleep(1)
view=self.getView(fieldName)
view2=self.getView('Add another field')
if view2:
if not view:
find=0
break
if 0==find:
trace('Step: add field '+fieldName+' info')
view2.touch()
trace('Click Add another field')
sleep(2)
view=self.getView(fieldName)
if not view:
view2=self.getView('id/no_id/2',iD=True)
self.slide('up',view2)
view=self.getView(fieldName)
view.touch()
sleep(1)
#view=self.getView(fieldName)
#view2=self.getView(view.getId()[:-2]+str(int(view.getId()[-2:])+6),iD=True)
#view2.type(content)
sleep(1)
self.device.type(content)
sleep(2)
else:
trace('Step: Edit field '+fieldName+' info')
view2=self.getView(view.getId()[:-2]+str(int(view.getId()[-2:])+6),iD=True)
self.wipe(view2)
sleep(1)
view2.type(content)
sleep(1)
def editDetails(self,nameOrNumber,company='',website='',nickname='',notes='',action='add'):
'''
'''
self.goEditExistContact(nameOrNumber)
if not company=='':
self.editCompany(company,action)
if not website=='':
self.editAnotherField('Website',website,action)
if not nickname=='':
self.editAnotherField('Nickname',nickname,action)
if not website=='':
self.editAnotherField('Notes',notes,action)
view=self.getView('Done')
trace('Click Done')
view.touch()
sleep(3)
self.goList()
def search(self,str):
'''
search contact by keyword
@type str: str
@param str: specify the search keyword
@return: the view of search result if search result is not null, else return False
'''
trace("start searching...")
try:
self.getView("Search",True).touch()
sleep(2)
self.device.type(str)
trace("search keyword is: "+str)
except AttributeError:
if self.isEmpty():
trace("No contacts exist")
else:
trace("No contacts searched")
return False
#the id of 1st search result is always 28
return self.getView("id/no_id/28",iD=True)
def sortAndViewAs(self, sort=True, first=True):
'''
sort and view contact name
@type sort: boolean
@param sort: whether sort contact name or view contact
@type first: boolean
@param first: whether sort and view contact by first name or last name
@return: boolean
'''
trace("start sorting...")
sleep(1)
self.goList()
self.menu()
self.scroll(times=4)
sleep(2)
sortOrView="Sort list by" if sort else "View contact names as"
firstOrLast="First name*" if first else "Last name*"
try:
self.getView(sortOrView).touch()
sleep(1)
self.getView(firstOrLast,regex=True).touch()
return True
except AttributeError:
return False
finally:
self.goList()
def favor(self,str,favor=True):
'''
add or cancel contact to favorites
@type str: str
@param str: specify the search string
@type favor: boolean
@param favor: add if True
'''
try:
self.search(str).touch()
sleep(3)
except AttributeError:
trace('no matched contact found, operation failed!')
self.goList()
return False
aim, action = ('Add to favorites', 'add') if favor else ('Remove from favorites', 'remov')
try:
self.getView(aim, cD=True).touch()
trace('%s successfully' % aim)
except AttributeError:
trace('%s has been %sed in favorites, not have to %s repeatedly' % (str, action, action))
sleep(3)
self.goList()
return True
def delete(self,kwd = ''):
'''delete one contact
@type kwd: string
@param kwd: keyword which contact to be delete, if none,delete first contact
@return:
'''
#self.start()
#trace('launch on contact application')
self.goList()
if self.isEmpty():
trace('Could not find any contact data,no record!')
raise SyntaxError('Could not find any contact data,no record!')
if not kwd :
# keyword is empty,delete first contact
trace('keyword is none, first contact with be delete')
find = self.getView('id/no_id/27',iD=True,dump=False)
#if find != None:
else :
# keyword is not none
# search specifying contact by keyword
find = self.search(kwd)
trace('')
# if find != None:
if not find :
trace('Could not find the contact : ' + kwd)
raise SyntaxError('Could not find the contact : ' + kwd)
else:
# delete operate
find.touch()
sleep(3)
trace('show contact detail information')
sleep(1)
self.device.press('KEYCODE_MENU')
sleep(4)
delete_menu = self.getView('Delete')
trace('choose delete contact')
delete_menu.touch()
# confirm delete operate
ok_menu = self.getView('OK')
ok_menu.touch()
sleep(3)
# if current activity is not Main Activity back to Main Activity
self.goList()
if 0 == self.getCounter() :
trace(' all contacts has been deleted, no record!')
trace('operation success.')
if __name__ == '__main__':
device=MonkeyRunner.waitForConnection()
trace('=' * 80)
trace('start testing...')
c=contacts(device)
trace('complete init')
c.start()
trace('complete contacts activity starting')
############################ add contact case Beginning ############################
c.favor('jason1')
'''
for i in range(5):
result='failed'
try:
before=c.getCounter()
c.addContact(name='jason',phone='123',email='[email protected]',address='softwarepark')
after=c.getCounter()
if after - before == 1:
result='passed'
# except Exception,e:
# result='unknown'
# details=str(e)
finally:
trace("*" * 20 + " case %d is %s " % (i + 1, result) + "*" * 20)
# if 'unknown' == result:
# trace('Exception details: ' + details)
sleep(5)
c.favor('jason')
c.favor('jason')
c.favor('jason',False)
c.favor('jason',False)
trace('end testing')
############################ add contact case Finished ############################
'''
for i in range(5):
#ss=c.search("moto")
#ss.touch()
print (i, i%2, i%3)
c.sortAndViewAs(i%2,i%3)