monkeyrunner hangs when making a connection to the device - android

Here's what I need to do. I have 2 devices which I need to test using monkeyrunner. It is an automated test using python and monkeyrunner. I want to execute the test simultaneously for the 2 devices so I thought of using thread.
here's the code
import threading
import datetime import os, sys
import ConfigParser from com.android.monkeyrunner
import MonkeyRunner, MonkeyDevice,MonkeyImage from datetime
import datetime import hashlib from java.net
import SocketException from com.ziclix.python.sql
import zxJDBC
def UseThread(data1, data2, data3, devID, Code, ScreenshotRef,
logFile):
device = MonkeyRunner.waitForConnection(10, devID)
'threaded code'
'initialization'
file = open(os.path.dirname(os.path.realpath(file)) +
'\Samples.txt','r') while 1:
while 1:
line = file.readline()
if not line:
print 'Done!'
break
else:
line
val=line.split('\t')
data1 = val[0]
data2 = val[1]
data3 = val[2]
threads = []
for Code in cp.options('p'):
devID = cp.get('product',Code).strip()
ScreenshotRef = cp.get('source','ScreenshotRef') + '\\' + prodCode.upper()
logFile = outputFolder + '\\' + prodCode.upper() + '\\logs.txt'
t=threading.Thread(target=UseThread,args=(data1, data2, data3, devID, prodCode, ScreenshotRef, logFile))
threads.append(t)
t.start()
for i in range(0,len(threads)):
threads[i].join()
The problem is this. When the while loops finish one run and proceed to 2nd run, the code hangs in the part when monkeyrunner is waiting for connection. To be exact, this is the part where it stops
device = MonkeyRunner.waitForConnection(10, devID)
the message says "Monkey command wake".
I assume that the problem has something to do with the connection, not with the thread because I tried to print something before that line which makes a connection and it works.
Is there an issue making a connection when you have already made one? do I need to close the previous connection first?

MonkeyRunner waitForConnection works only for one device. You cannot run this twice. You can run from another instance

Related

Python: Run multiple commands simultaneously [duplicate]

This question already has answers here:
Executing multiple functions simultaneously
(6 answers)
Closed 6 years ago.
I have two android devices connected to my Linux machine and I need to be able to take a screenshot on both at the exact same time. How can I achieve this in python?
This is what I have so far:
import time, datetime
from threading import Thread
from Queue import Queue
def get_screenshot(deviceid):
print deviceid
print datetime.datetime.now()
# Logic to get screenshot goes here
deviceids = ["blabla1", "blabla2"]
q = Queue()
for d in deviceids:
t = Thread(target=get_screenshot, args=(d,))
t.setDaemon(True)
t.start()
for d in deviceids:
q.put(d)
q.join()
The output looks like this:
blabla1
2016-10-02 12:55:17.146964
blabla2
2016-10-02 12:55:17.147141
The problem is:
1. Is the approach correct?
2. Why the difference of 1ms? Can that be avoided?
3. This program does not exit. I need to Ctrl+Z out of it.
import datetime
from threading import Thread
def get_screenshot(deviceid):
print("%s %s" %(deviceid, datetime.datetime.now()))
deviceids = ["blabla1", "blabla2"]
for d in deviceids:
t = Thread(target=get_screenshot, args=(d,))
t.start()
You don't need a queue.
0.2 ms wasted on thread creation and starting.
It's because you put strings into the Queue and than join that queue - the queue 'waits for strings' and hangs. Do you really need to join your threads? You may write your screenshots to files in the thread function. Python program automatically closes when all it's threads are finished.

Android monkey runner usage

I have a simple requirement to run a set of files on url on MediaPlayer.
I am writing a script to do this.
There is a variable mediapath in MainActivity.java which takes url path.
Is it possible to give this variable url value using android monkeyrunner script.
currently there is no device.set function to set the particular value.
My script is:
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
device = MonkeyRunner.waitForConnection()
package = 'com.example.diagplayer'
activity = 'com.example.diagplayer.MainActivity'
file = open('filelist.txt', 'r')
rows = file.readlines()
for file_name in rows:
uri=file_name
extra = {}
extra['URI']=uri
print(uri)
runComponent = package + '/' + activity
device.set("MediaPath","uri")//getting error here
device.touch(100, 350, MonkeyDevice.DOWN)
device.touch(10,350, 'DOWN_AND_UP')
It would be impossible for a device.set() method to set a variable in a running Activity, which I think is your intention.
However you can set the extras of the Intent with the desired values (as you did) and then make your Activity extract them and set the variables.

urlopen error [errno 111] connection refused

I am doing python exercise with a book 'headfirst python'
and making android app by using python and sl4a
my code is
import android
import json
import time
from urllib import urlencode
from urllib2 import urlopen
hello_msg = "Welcome to Coach Kelly's Timing App"
list_title = 'Here is your list of athletes:'
quit_msg = "Quitting Coach Kelly's App."
web_server = 'http://127.0.0.1:8080'
get_names_cgi = '/cgi-bin/generate_name.py'
def send_to_server(url, post_data=None):
if post_data:
page = urlopen(url, urlencode(post_data))
else:
page = urlopen(url)
return(page.read().decode("utf8"))
app = android.Android()
def status_update(msg, how_long=2):
app.makeToast(msg)
time.sleep(how_long)
status_update(hello_msg)
athlete_names = sorted(json.loads(send_to_server(web_server + get_names_cgi)))
app.dialogCreateAlert(list_title)
app.dialogSetSingleChoiceItems(athlete_names)
app.dialogSetPositiveButtonText('Select')
app.dialogSetNegativeButtonText('Quit')
app.dialogShow()
resp = app.dialogGetResponse().result
status_update(quit_msg)
this is my code and the result is
what is the problem???
I can not figure out what the problem is...
Use 10.0.2.2:8080
because If you are running both server and emulator in you computer 127.0.0.1:(port) the local IP will refer to the emulator then you need another local IP for the server which will be automatically The 10.0.2.2
hope i clearified it well, glad i helped
Having followed #Coderji 's solution, I was finally able to solve this problem albeit with a different IP address; since the suggested 10.0.2.2 didn't work for me.
What worked for me was to access a terminal, ipconfig, and then used any of the provided ipv4 addresses provided by cmd (all of them seemed to work). Cheers.

How to launch activity "ACTION_SYNC_SETTINGS" or "ACTION_ADD_ACCOUNT" using monkeyrunner (Python script)

I am trying to start activity ACTION_SYNC_SETTINGS or ACTION_ADD_ACCOUNT which are in package android.provider.Settings but, the problem is these activities do not start.
My code is given below, which works for launching activity "Settings" but when I change activity by ACTION_SYNC_SETTINGS or SYNC_SETTINGS ; ACTION_ADD_ACCOUNT or ADD_ACCOUNT_SETTINGS then it odes not work...
Although, I tried with package com.android.provider.Settings too, but it did not work.
The only result I get is:
Monkey Command: wake.
Monkey Command: wake.
Monkey Command: quit.
(I am working at API level 10 and 15)
Please can any one guide me...?
My Code:
import os, subprocess
import sys
import time
import random
import string
import re
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
device = MonkeyRunner.waitForConnection(99, "emulator-5554")
package='com.android.settings'
activity='.Settings'
component_name=package + "/" + activity
device.startActivity(component=component_name)
Try to use:
component = 'com.android.settings/.accounts.AddAccountSettings'
This will open the "Add an account" window where you can choose from Corporate, Email and Google.
Choosing Google will start a new activity: com.google.android.gsf.login/.AccountIntroUIActivity
To go directly to the sign in screen, use:
device.startActivity(component = 'com.google.android.gsf.login/.LoginActivity')

Is "Monkey Runner" useful for testers to prepare test cases directly in Android applications?

I have gone through the "Monkey Runner" for the following link
http://developer.android.com/guide/topics/testing/testing_android.html
It has so much Java code. I am not able to under stand the code to create test cases. Is it only for developers, or the testers to test the application thoroughly. Is there any other pattern for creating test cases through code? Can any one suggest me about the same.
Thank you.
Have a look at my MonkeyRunner code. Should be easier then Java. Change path to save file, and replace phone number. I had only 1 problem. Cant Hangup a call.
#! /usr/bin/env monkeyrunner
'''
Created on Apr 1, 2011
#author: sj
'''
import sys
# import the MonkeyRunners modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
def browse(d):
d.broadcastIntent("http://www.google.com/", "ACTION_MAIN")
#d.startActivity(component="com.android.browser/.BrowserActivity")
def debug(device):
print" package:%s" % device.getProperty('am.current.package')
print" action:%s" % device.getProperty('am.current.action')
print" comp.class:%s" % device.getProperty('am.current.comp.class')
print" comp.package:%s" % device.getProperty('am.current.comp.package')
print device.getProperty('display.width'), device.getProperty('display.height')
def screenshot(d):
MonkeyRunner.sleep(1.0)
result = d.takeSnapshot()
MonkeyRunner.sleep(1.0)
result.writeToFile('/yourPath/device.png', 'png')
def call(d):
d.startActivity(component="com.android.contacts/.TwelveKeyDialer")
print "Start Activity"
MonkeyRunner.sleep(1.0)
d.type("+XXXXXXXX")
# Call number.
print "Call"
d.touch(190, 800, 'DOWN_AND_UP');
# not working device.press('KEYCODE_CALL', 'DOWN_AND_UP')
print "Wait 10 sec"
MonkeyRunner.sleep(10.0)
# HangUp Call
#device.press('KEYCODE_ENDCALL', 'DOWN_AND_UP')
print "Hang Up"
#x1 = 215
#x2 = 230
#y = 700
#start = (x1,y)
#end = (x2, y)
#steps = 2
#pause = 0.2
#device.drag(start, end, pause, steps)
d.startActivity(component="com.android.phone/.InCallScreen")
#device.touch(230, 700, "DOWN");
MonkeyRunner.sleep(1.0)
#device.touch(230, 700, "UP");
d.touch(230, 700, 'DOWN_AND_UP');
#device.touch(270, 650, 'DOWN_AND_UP');
def main():
print "Start"
# Connect to the current device returning the MonkeyDevice object
device = MonkeyRunner.waitForConnection()
#MonkeyRunner.alert("Starting Activity", "monkeyrunner", "OK")
if not device:
print "Couldn't get connection"
sys.exit()
print "Found device"
#call(device)
browse(device)
debug(device)
screenshot(device)
device.press('KEYCODE_ENDCALL', 'DOWN_AND_UP')
MonkeyRunner.sleep(10.0)
if __name__ == '__main__':
main()
I have learned monkeyrunner via this small guide.
http://antoine-merle.com/introduction-to-the-monkey-runner-tool-2/
You do not have to use java, but to start low on python. For the ide you can use pycharm, which will give you a better start when creating classes in python.
As of the code which #Boris_Ivanov showed, this is a good start, but I would delete the "MonkeyImage" - as you are not using it also pushing the test cases into different files would add to speed if required to use.
One thing to talk about:
Connect to the current device returning the MonkeyDevice object
device = MonkeyRunner.waitForConnection()
#MonkeyRunner.alert("Starting Activity", "monkeyrunner", "OK")
I am using something like this and it does work all the way:
device = MonkeyRunner.waitForConnection(60)
if not device:
raise Exception('Can not connect to device')
Best luck.

Categories

Resources