Sikuli api - "OK" click ignored during file upload - python-2.7

Using:
Sikuli-api stand alone jar
python 2.7.6 with pyjnius
Ubuntu 14.04 Trusty
Issue:
The Sikuli DesktopMouse click() method works in almost all situations except when I'm trying to click "Open" on a file upload [Ubuntu Open](http://i.stack.imgur.com/nZsvv.png) from the upload dialog or "Allow" on the Flash Player Settings dialog [Flash Player Settings](http://i.stack.imgur.com/7OrbG.png). If I navigate to these areas manually I can click on these buttons without error. I have to imagine that it is some sort of permissions issue (because all other clicks work including all the clicks in the code snippet below. I mean, the exception at the bottom is thrown, meaning that the "Open" button is both seen and clicked on, twice), but I haven't the foggiest what that would entail. There are no errors to share because the click doesn't technically fail
About Code:
self.get_target() returns an ImageTarget
self.mouse and self.kb are instances of DesktopMouse and DesktopKeyboard respectively.
self.box creates a DesktopCanvas and draws a box around the target DesktopScreenRegion
Code:
def upload_file(self, path, title):
screen = sikuli.DesktopScreenRegion()
locationTarget = self.get_target("images/ubuntu_location_field.png")
locationTarget.setMinScore(.6)
locationField = screen.wait(locationTarget, 5000)
if locationField is None:
editTarget = self.get_target("images/ubuntu_location_edit.png")
edit = screen.wait(editTarget, 5000)
if edit is None:
searchTarget = self.get_target("images/ubuntu_upload_search.png")
search = screen.wait(searchTarget, 5000)
self.box(search)
self.mouse.click(search.getCenter())
else:
self.box(edit)
self.mouse.click(edit.getCenter())
locationField = screen.wait(locationTarget, 5000)
self.mouse.click(locationField.getCenter())
self.kb.type(path + "/" + title)
okTarget = self.get_target("images/ubuntu_upload_opensave.png")
ok = screen.find(okTarget)
self.mouse.click(ok.getCenter())
if screen.find(okTarget):
self.mouse.click(ok.getCenter())
if screen.find(okTarget):
#GETTING TO THIS POINT MEANS THAT THE BUTTON CAN BE SEEN AND CLICKED
#BUT THAT THE CLICK IS NOT DOING ANYTHING
raise Exception("Upload file is acting like a bitch.")
sikuli.API.pause(10000)

Found that the issue stemmed from using the firefox webdriver, which apparently has much higher security than its chrome counterpart. All operations can be done on chromedriver.

Related

wxpython how to set a bind event on a button which gets enable upon clicking on other button

which consist a combo box 4 buttons. Once i select an entry from combo box, it will enable a button upon clicking one button it enables the rest. I want to send a command once the buttons is enabled on clicking it.
Below is my code:
import wx
import xlrd
import os,sys,time
folderpath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
print folderpath
site_lib_path = os.path.join(folderpath, "site_lib")
files = os.listdir(site_lib_path)
for file in files:
sys.path.append(os.path.join(site_lib_path, file))
from printercx import printercx
from resttestservice.resttestservice import UITest
class ui(wx.Frame):
"""
This Class will create a Sample Frame and Create Two Buttons on tha Panel.
"""
def __init__(self,parent,id):
"""
This Fucntion will create a Frame and a Panel which has Two buttons: "OK" and "Cancel"
"""
"""-----SALQE Connecttion-----------"""
self.connection = printercx.deviceConnection()
self.ui = UITest(self.connection)
"""-----------Window Bar Name------"""
wx.Frame.__init__(self,parent,id,'GEN-2 Tool',size=(600,500))
panel=wx.Panel(self)
"""-----------Heading-------"""
header_text = wx.StaticText(panel, label="GEN-2 Tool", pos=(250,30))
font = wx.Font(15, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
header_text.SetFont(font)
wx.StaticLine(panel, pos=(10, 75), size=(690,3))
"""-----------Buttons-------"""
self.pre_button=wx.Button(panel,label="Precondition",pos=(50,250),size=(100,40))
self.act_button=wx.Button(panel,label="Action",pos=(450,250),size=(100,40))
self.pass_button=wx.Button(panel,label="Pass",pos=(50,350),size=(100,40))
self.fail_button=wx.Button(panel,label="Fail",pos=(450,350),size=(100,40))
"""-------------------------------Excel-------------------------------------------------------"""
self.mainList=[]
self.val_list=[]
dic={}
book=xlrd.open_workbook("Reference_Mapping.xlsx")
sheet=book.sheet_by_name("TestCases")
n_row= sheet.nrows-1
n_col=sheet.ncols
row=1
while row<=n_row:
smallList=[]
col=0
while col<n_col:
cel=sheet.cell(row,0)
if cel.value!="":
self.val_list.append(cel.value)
key=sheet.cell(0,col).value
val=sheet.cell(row,col).value
dic[key]=val
col+=1
smallList.append(dic.copy())
self.mainList.append(smallList)
row+=1
self.val_list= list(set(self.val_list))
"""-------------------------------------------------------------------------------------------------"""
"""-----------Combo Box with Text-------"""
text=wx.StaticText(panel, label="Test Case: ", pos=(150,130))
font = wx.Font(10,wx.DECORATIVE, wx.NORMAL, wx.BOLD)
text.SetFont(font)
self.val_list.insert(0, "Select")
self.combobox=wx.ComboBox(panel, value=self.val_list[0], pos=(300,130), choices=self.val_list,style=wx.CB_READONLY)
self.Bind(wx.EVT_COMBOBOX, self.onTestCaseSelection, self.combobox)
print "-----------"
def onTestCaseSelection(self,event):
if self.combobox.GetSelection()>0:
print self.combobox.GetValue()
"""---------- Compairing Key's values--------------"""
for each in range(len(self.mainList)):
for every in range(len(self.mainList[each])):
if self.mainList[each][every]['TC_ID']==self.combobox.GetValue():
if self.mainList[each][every]['Ref_ID_Pre']=="":
if self.mainList[each][every]['Ref_ID_Post']!="":
self.pre_button.Enable(False)
self.act_button.Enable(True)
self.Bind(wx.EVT_BUTTON,self.send_udw,self.act_button)
self.pass_button.Enable(True)
self.fail_button.Enable(True)
if self.mainList[each][every]['Ref_ID_Pre']!="":
if self.mainList[each][every]['Ref_ID_Post']=="":
self.pre_button.Enable(True)
self.Bind(wx.EVT_BUTTON,self.send_udw,self.pre_button)
self.act_button.Enable(False)
self.pass_button.Enable(False)
self.fail_button.Enable(False)
if self.mainList[each][every]['Ref_ID_Pre']!="":
if self.mainList[each][every]['Ref_ID_Post']!="":
action_button_cmd=self.mainList[each][every]['Ref_ID_Post']
self.pre_button.Enable(True)
self.Bind(wx.EVT_BUTTON,self.send_udw,self.pre_button)
self.act_button.Enable(False)
self.pass_button.Enable(False)
self.fail_button.Enable(False)
else:
self.disableAllControls(without=None)
def disableAllControls(self, without=None):
if without==None:
self.pre_button.Enable(False)
self.act_button.Enable(False)
self.pass_button.Enable(False)
self.fail_button.Enable(False)
def send_udw(self,event):
for each in range(len(self.mainList)):
for every in range(len(self.mainList[each])):
if self.mainList[each][every]['TC_ID']==self.combobox.GetValue():
if self.mainList[each][every]['Ref_ID_Pre']=="":
if self.mainList[each][every]['Ref_ID_Post']!="":
if self.act_button.IsEnabled()==True:
post_command=self.mainList[each][every]['Ref_ID_Post']
post_udw="ui_v3.move_to_state "+post_command+" 1"
self.connection.udw(post_udw)
if self.mainList[each][every]['Ref_ID_Pre']!="":
if self.mainList[each][every]['Ref_ID_Post']=="":
if self.pre_button.IsEnabled()==True:
post_command=self.mainList[each][every]['Ref_ID_Pre']
post_udw="ui_v3.move_to_state "+post_command+" 1"
self.connection.udw(post_udw)
if self.mainList[each][every]['Ref_ID_Pre']!="":
if self.mainList[each][every]['Ref_ID_Post']!="":
if self.pre_button.IsEnabled()==True:
post_command=self.mainList[each][every]['Ref_ID_Pre']
post_udw="ui_v3.move_to_state "+post_command+" 1"
print post_udw
self.connection.udw(post_udw)
"""----Enabling button---"""
self.pre_button.Enable(False)
self.act_button.Enable(True)
self.pass_button.Enable(True)
self.fail_button.Enable(True)
time.sleep(1)
I want to send a command once this button self.act_button.Enable(True) gets enabled.
You can bind the button's to events before you disable them. They aren't going to react to events (other than maybe mouse events) until you enable them. There is no reason to bind events when you enable the button.
If you want to call a function after the enabling process (i.e. self.act_button.Enable(True)), then just call the function right after that:
self.act_button.Enable(True)
self.myFunction(*args, **kwargs)
If you want to create some kind of custom event, then you'll want to look into how to use wx.PostEvent and wx.lib.newevent. The following resources might interest you as well:
https://wiki.wxpython.org/CustomEventClasses
https://wxpython.org/Phoenix/docs/html/events_overview.html
http://wiki.ozanh.com/doku.php?id=python:misc:wxpython_postevent_threading

[Python2.7 TKinter]How to gray out a option in optionmenu that has been selected by older instances?

Here's my code:
class DefaultServiceClassWidget(ServiceClassWidget):
def __init__(self, mpet_widget, sc_data, idx):
super(DefaultServiceClassWidget, self).__init__(mpet_widget, sc_data, idx, DefaultServiceClassRow.number)
delete_default_sc_button = Button(mpet_widget.listFrame,justify=LEFT,text="x",fg="red",command= lambda: mpet_widget.delete_sc(self.idx))
delete_default_sc_button.grid(column=4,row=DefaultServiceClassRow.number)
self.select_default_class_label = Label(mpet_widget.listFrame,anchor=W,justify=LEFT,text="Select a Class")
self.select_default_class_label.grid(column=0,row=DefaultServiceClassRow.number)
options = ["All","CS Registration","GPRS Attach","PDP Activation","SMS","Reset","USSD","LTE"]
self.menu_pick_a_class = OptionMenu(mpet_widget.listFrame, sc_data.get_name(), *options, command=lambda event: sc_data.set_id())
self.menu_pick_a_class.grid(column=1,row=DefaultServiceClassRow.number)
self.row = DefaultServiceClassRow.number
DefaultServiceClassRow.number = DefaultServiceClassRow.number+2
def delete(self):
DefaultServiceClassRow.number = DefaultServiceClassRow.number - 2
default_list = (list(self.mpet_widget.listFrame.grid_slaves(row=self.row)) +
list(self.mpet_widget.listFrame.grid_slaves(row=self.row+1)))
for l in default_list:
l.grid_remove()
What happens is that there's a button connected to this function, every time the button is clicked, this function gets called and created a new grid on the GUI. What I want is that if for example "SMS" in optionmenu is selected, the next time this function gets called, "SMS" option will be grayed out (i.e. each option can be only selected once in the program)
I've tried updating status of the selected option by using status = "disabled" but it only works for the same grid, once a new grid(instance) is created, everything gets reset and all the options became available again :(
Also, in the same grid, if I disabled an option by selecting it and then changed to something else, the original selection is still grayed and cannot be selected again - I know why this happens but how do I fix it?
Sorry for the long question but I can't seem to find a solution online :(
Thank you in advance!

messagebox getting looped

I am displaying a message box on click of option menu when data is not available and is to be acquired. But somehow whenever I change content of the option menu the message box gets looped. Like- first time it vanishes when I press ok. when I change option again second time it displays message box two times and third time three times. Can someone tell me what to change in my code?
#the function where I change option menu value
def module_func(event):
#declarations
if(dateText.get()!="" and driveText.get()!=""):
global module_dir
global selected_module
modules['menu'].delete(0,END)
select="-----Select-----"
modules['menu'].add_command(label=select, command=tk._setit(module,select))
for module_dir in get_immediate_subdirectories(('%s\%s\%s')%(startPath,selected_shot,selected_fec)):
module_dropdown.append(module_dir)
modules['menu'].add_command(label=module_dir, command=tk._setit(module,module_dir))
module.trace('w',setEightText) #think problem is here
else:
errormsg("")
def setEightText(*args):
#declarations
if(os.path.exists(('%s\%s\%s\%s\%s')%(startPath,selected_shot,selected_fec,selected_module,chan))):
#some operations
else:
tkMessageBox.showinfo("Error","Data at given location not available.\n Please Wait until data is acquired.")
module=tk.StringVar(labelframe1)
module.set("-----Select-----")
modules = tk.OptionMenu(labelframe1, module, module_dropdown, command=module_func)
modules.config(width=20, background="SNOW")
modules.grid(row=8, column=2, sticky="W", padx=10, pady=5)
modules.bind('<Button-1>',module_func)
I think the problem is because of trace. But don't know what to add instead of that.

Tkinter bind executes immediately when script is run

I've laid out a frame, part of which is:
ticketID = IntVar()
ticketID.set(ticket)
ticketfield = Label(titleframe, text = 'Ticket : ')
ticketfield.grid(row=0, column=0)
ticketfieldentry = Entry(titleframe, textvariable=ticketID)
ticketfieldentry.grid(row=0, column=1)
ticketfieldentry.bind("<Double-Button-1>", searchforticket(ticketfieldentry.get()))
And a placeholder:
def searchforticket(ticket):
searchforstring = "This would search for ticket %s" % ticket
tkMessageBox.showinfo('Search by ticket', message = searchforstring)
Ticket is passed to the script at run time, or is assumed None. What I thought the above would do is create an Entry box that would display the ticket number, or could have one entered directly. After being entered, double clicking would bring up the searchforticket function.
However, when I run the script, searchforticket is run immediately, with whatever is being assigned to ticket and then after I click past the tkMessageBox is when the window containing the ticketfieldentry and everything else renders.
I am not seeing at all what could be causing this, but I assume it is something dead obvious to someone else.
searchforticket(ticketfieldentry.get() cause immediate call. Change as follow:
ticketfieldentry.bind("<Double-Button-1>", lambda e: searchforticket(ticketfieldentry.get()))

how to display an accelerator for a Gio.MenuItem

I'm trying to display the shortcut key accelerator for a Gio.Menuitem
As you can see, the RandomAlbum menu item does not have an accelerator displayed - however, I have added added the accelerator and connected it to the Gio.MenuItem successfully because the menuitem responds to the keyboard shortcut Alt+Z
The snippet of code I'm using is as follows:
action = Gio.SimpleAction.new(action_name, None)
app = Gio.Application.get_default()
app.add_accelerator("<alt>Z", "app."+action_name, None)
item = Gio.MenuItem()
item.set_detailed_action('app.' + action_name)
item.set_label("RandomAlbum")
app.add_plugin_menu_item('tools', "unique name", item)
Any ideas why the accelerator does not display - but still responds to keyboard control?
The full source is here:
https://github.com/fossfreedom/Rhythmbox-Random-Album-Player
The missing piece of this jigsaw puzzle is realising that Gio.MenuItems themselves have attribute-values.
So in this case, before adding the menu-item to the GMenu the syntax required is:
item.set_attribute_value("accel", GLib.Variant("s", "<Alt>Z"))
To complete the answer, you can also set the label and action for the menu-item in this way:
item = Gio.MenuItem()
item.set_attribute_value("label", GLib.Variant("s", "RandomAlbum"))
item.set_attribute_value("action", GLib.Variant("s", "app."+action_name))
However the methods set_label and set_detailed_action perform the same role.