Salome HOME
Merge branch 'BR_v14_rc' of ssh://git.salome-platform.org/modules/hydro into BR_v14_rc
[modules/hydro.git] / squish.suite / shared / scripts / common.py
1 """Common functions"""
2 import os
3 import datetime, time
4
5
6 """
7 Check that Object Browser is displayed.
8 """
9 def checkObjectBrowser():
10     waitFor("object.exists(':Object Browser_QtxTreeView')", 20000)
11     test.compare(findObject(":Object Browser_QtxTreeView").visible, True)
12     
13 """
14 Check that Python console is displayed.
15 """
16 def checkPythonConsole():
17     waitFor("object.exists(':Python Console_PyConsole_EnhEditor')", 20000)
18     test.compare(findObject(":Python Console_PyConsole_EnhEditor").visible, True)
19
20 """
21 Activate menu for any level of depth.
22 For example:  activateMenuItem("File","New")
23 """
24 def activateMenuItem(*menuPath):
25     menu = ":SALOME_QMenuBar"
26     parent = "{type='STD_TabDesktop' unnamed='1' visible='1' windowTitle?='SALOME *'}"
27     for item in menuPath[:-1]:
28         activateItem(waitForObjectItem(menu, item))
29         menu = "{title='%s' type='QMenu' unnamed='1' visible='1'}" % (item) 
30         parent = menu
31     activateItem(waitForObjectItem(menu, menuPath[-1]))
32    
33 """
34 Return current data in given format
35 """    
36 def getCurrentDateString(format = "%d/%m/%Y %H:%M"):
37     now = datetime.datetime.now()
38     return str(now.strftime(format))
39
40 """
41 Return current user name
42 """    
43 def getCurrentUser():
44      user = os.getenv("USER")
45      return user
46
47 """
48 Return difference between given and current date 
49 """ 
50 def dateDifferenceToNow(date_str, format="%d/%m/%Y %H:%M"):
51     now = datetime.datetime.now()
52     date_to_compare = datetime.datetime(*(time.strptime(date_str, format)[0:6]))
53     test.log("dateDifferenceToNow","now:"+str(now)+" date_to_compare:"+str(date_to_compare)+"  dif:"+ str(now-date_to_compare))
54     return abs(now - date_to_compare)< datetime.timedelta(minutes = 1)
55
56
57 #--------------------------------------------------------------------------
58 # Menu File
59 #--------------------------------------------------------------------------
60 """
61 Open given file via menu "File"-"Open"
62 For example:  openFile("/<Full path to file>")
63 """    
64 def openFile(file_path):
65     activateMenuItem("File","Open...")
66     test.verify(os.path.exists(file_path))
67     realName = "{buddy=':Open File.File name:_QLabel' name='fileNameEdit' type='QLineEdit' visible='1'}"  #:fileNameEdit_QLineEdit_2
68     waitForObject(realName).setText(file_path)
69     type(waitForObject(realName), "<Return>")
70     
71 """
72 Save given file via menu "File"-"Save As"
73 For example:  saveFile("/<Full path to file>")
74 """    
75 def saveFile(file_path):
76     activateMenuItem("File","Save As...")
77     lineEditRealName = "{buddy=':Save File.File name:_QLabel' name='fileNameEdit' type='QLineEdit' visible='1'}"
78     saveBtnRealName = "{text='Save' type='QPushButton' unnamed='1' visible='1' window=':Save File_SUIT_FileDlg'}"#{text='Save' type='QPushButton' unnamed='1' visible='1' window=':Save File_SUIT_FileDlg'}
79     waitFor("object.exists('%s')" % lineEditRealName.replace("'", "\\'"), 2000)
80     waitForObject(lineEditRealName).setText(file_path)
81     type(waitForObject(lineEditRealName), "<Return>")
82
83 """
84 Import Python script via SALOME Python console
85 For example:  importPythonScript("SMESH_test1")
86 """
87 def importPythonScript(fileName):
88     mouseClick(waitForObject(":Python Console_PyConsole_EnhEditor"), 50, 10, 0, Qt.LeftButton)
89     type(waitForObject(":Python Console_PyConsole_EnhEditor"), "import %s" % fileName)
90     type(waitForObject(":Python Console_PyConsole_EnhEditor"), "<Return>")
91     
92 """
93 Call File->Close menu
94 """ 
95 def closeFile():
96     activateMenuItem("File","Close")
97
98 """
99 Makes dump of the study to given file via menu
100 File->Dump study
101 """
102 def dumpStudy(file_path, save_gui_state = False ):
103     activateMenuItem("File","Dump Study...")
104     waitForObject(":Dump study.Save GUI state_QCheckBox").checked = save_gui_state
105     mouseClick(waitForObject(":fileNameEdit_QLineEdit_3"), 20, 11, 0, Qt.LeftButton)
106     waitForObject(":fileNameEdit_QLineEdit_3").setText(file_path)
107     type(waitForObject(":fileNameEdit_QLineEdit_3"), "<Return>")
108
109 """
110 Opens python script via menu File->Load Script
111 """
112 def loadScript(file_path):
113     activateMenuItem("File","Load Script...")
114     mouseClick(waitForObject(":fileNameEdit_QLineEdit_4"), 45, 12, 0, Qt.LeftButton)
115     waitForObject(":fileNameEdit_QLineEdit_4").setText(file_path)
116     clickButton(waitForObject(":Load python script.Open_QPushButton"))     
117
118
119 #--------------------------------------------------------------------------
120 # Object browser
121 #--------------------------------------------------------------------------
122 """
123 Deselect all objects selected in Object browser.
124 """
125 def deselectAll():
126     objBrowser = waitForObject(":Object Browser_QtxTreeView")
127     objBrowser.clearSelection()   
128
129 """
130 Select item in Object Browser tree under topTreeItem with possible modifier.
131 The mostly used values  of modifier are Qt.ShiftModifier, Qt.ControlModifier
132 """  
133 def selectObjectBrowserItem(item, topTreeItem = "HYDRO" , modifier =  0 ):
134     itemText = getItemText(item, topTreeItem) 
135     waitForObjectItem(":Object Browser_QtxTreeView",  itemText)
136     clickItem(":Object Browser_QtxTreeView", itemText, 30, 5, modifier, Qt.LeftButton)
137
138 """
139 Verify that given item exists in Object Browser
140 For example: checkOBItemNotExists("HYDRO", "NATURAL OBJECTS", "Immersible zone_1")
141 """ 
142 def checkOBItem(*parentNames):
143     treeObj = waitForObject(":Object Browser_QtxTreeView")
144     obj = getModelIndexByName(treeObj, *parentNames)
145     if (not obj is None) and obj.isValid(): 
146         test.compare(obj.text, parentNames[-1])
147     else:
148         s=""
149         for name in parentNames:
150             s +="/"+str(name)
151         test.fail("Unexpectedly failed to find the object in OB", s)
152
153 """
154 Verify that given item doesn't exist in Object Browser
155 For example: checkOBItemNotExists("HYDRO", "NATURAL OBJECTS", "Immersible zone_2")
156 """ 
157 def checkOBItemNotExists(*parentNames):
158     treeObj = waitForObject(":Object Browser_QtxTreeView")
159     obj = getModelIndexByName(treeObj, *parentNames)
160     s=""
161     for name in parentNames:
162         s +="/"+str(name)
163     if (not obj is None) and obj.isValid(): 
164         test.fail("Unexpectedly object is found in OB", s)
165     else:
166         test.passes("Object '%s' wasn't found in OB" % s)    
167             
168 """
169 Activate context menu item for the given object in the Object Browser.
170 For example: aactivateOBContextMenuItem("HYDRO.NATURAL OBJECTS", "Zone_1", "Show")
171 """
172 def activateOBContextMenuItem(parent, item, *menuPath):
173     try:
174         name = getItemText(item, parent)
175         selectObjectBrowserItem(item, parent)
176         openItemContextMenu(waitForObject(":Object Browser_QtxTreeView"), name, 10, 1, 0)
177         popupItem(*menuPath)
178     except LookupError,err:
179         test.fail("Unexpectedly failed to find the object in OB", str(err))
180
181 """
182 Activate context menu item for the given list of objects in the Object Browser.
183 For example:  activateOBContextMenuItems("HYDRO.NATURAL OBJECTS", ["Zone_1", "Zone_2"], "Show")
184 """
185 def activateOBContextMenuItems(topTreeItem, listItems, *menuPath):
186     itemText = ""
187     selectObjectBrowserItem(listItems[0], topTreeItem)
188     for item in listItems[1:]:
189         itemText = getItemText(item, topTreeItem) 
190         waitForObjectItem(":Object Browser_QtxTreeView",  itemText)
191         clickItem(":Object Browser_QtxTreeView", itemText, 30, 5, Qt.ControlModifier, Qt.LeftButton)
192     openItemContextMenu(waitForObject(":Object Browser_QtxTreeView"), itemText, 10, 1, 0)
193     popupItem(*menuPath)    
194
195 #--------------------------------------------------------------------------
196 # OCC Viewer
197 #--------------------------------------------------------------------------
198 """
199 Activate context menu item at the given point of 3D viewer.
200 For example: activateOCCViewerContextMenuItem(100, 100, "Hide all")
201 """   
202 def activateOCCViewerContextMenuItem(x, y, *menuPath): 
203     activateViewerContextMenuItem(":SALOME *.3D View Operations_OCCViewer_ViewPort3d", x, y, *menuPath)
204
205 """
206 Click "Fit All" button
207 If isDeselectAll = True all selected objects will be deselected.
208 """ 
209 def fitAll(isDeselectAll=False):
210     if isDeselectAll:
211         deselectAll()
212     clickButton(waitForObject(":SALOME *.Fit All_QToolButton"))
213
214 """
215 Click "Reset" button
216 """ 
217 def resetOCCViewer():
218     clickButton(waitForObject(":SALOME *.Reset_QToolButton"))
219
220 """
221 Show/Hide trihedron axis in OCC Viewer
222 """
223 def showTrihedron(val):
224     btn = waitForObject(":SALOME *.Show/Hide trihedron_QToolButton")
225     if btn.checked != val:
226         clickButton(btn)
227 """
228 Call Transparency popup menu in OCC Viewer
229 """
230 def setOCCViwerTransparency(value, pos_x = -1, pos_y = -1 ):
231     setTransparency(":SALOME *.3D View Operations_OCCViewer_ViewPort3d", value, pos_x, pos_y)
232     
233 """
234 Call Isos popup menu in OCC Viewer
235 """
236 def setOCCViwerIsos(u, v, pos_x = -1, pos_y = -1):
237     setIsos(":SALOME *.3D View Operations_OCCViewer_ViewPort3d", u, v, pos_x, pos_y)
238
239 #--------------------------------------------------------------------------
240 # VTK Viewer
241 #--------------------------------------------------------------------------
242     
243 """
244 Activate context menu item at the given point of VTK viewer.
245 For example:  activateVTKContextMenuItem(50, 100, "Hide")
246 """
247 def activateVTKContextMenuItem(x, y, *menuPath):
248     activateViewerContextMenuItem(":SALOME *.SVTK_RenderWindowInteractor_SVTK_RenderWindowInteractor", x, y, *menuPath)
249
250 def setVTKIsos(u, v, pos_x = -1, pos_y = -1):
251     setIsos(":SALOME *.SVTK_RenderWindowInteractor_SVTK_RenderWindowInteractor", u, v, pos_x, pos_y)
252
253 def setVTKTransparency(value, pos_x = -1, pos_y = -1 ):
254     setTransparency(":SALOME *.SVTK_RenderWindowInteractor_SVTK_RenderWindowInteractor", value, pos_x, pos_y)
255     
256
257 #--------------------------------------------------------------------------
258 # Widgets
259 #--------------------------------------------------------------------------
260 """
261 Set button checked or unchecked
262 """
263 def setButtonChecked(button, isChecked):
264     if (isChecked != button.checked):
265         clickButton(button)
266
267     test.verify(button.checked == isChecked)
268
269 """
270 Select item with the given text in the combo box
271 """
272 def selectComboBoxItem(combo, itemText):
273     for index in range(combo.count):
274         if combo.itemText(index) == itemText:
275             combo.setCurrentIndex(index)
276             break
277         
278     test.verify(combo.currentText == itemText)
279     pass
280
281 """
282 Check that the combo box contains only the given items.
283 """
284 def checkComboBoxContent(combo, items):
285     sortItems = list(items)
286     sortItems.sort()
287     
288     comboItems = []
289     for index in range(combo.count):
290         comboItems.append(str(combo.itemText(index)))
291     
292     comboItems.sort()
293         
294     test.compare(comboItems, sortItems)
295     pass
296     
297 #--------------------------------------------------------------------------
298 # Internal methods
299 #--------------------------------------------------------------------------
300
301 """
302 Returns the QModelIndex for child with given name and parent index
303 Warning: may works incorrectly for items with duplicated names   
304 """    
305 def getChildModelIndex(parentIdx, name):
306     row=0
307     if parentIdx is None:
308         return None
309     childIdx = parentIdx.child(row, 0)
310     while childIdx.isValid():
311         if name == str(childIdx.data().toString()):
312             return childIdx
313         row += 1
314         childIdx = childIdx.sibling(row, 0)
315     return None    
316
317 """
318 Returns the QModelIndex form given tree by list of hierarchical names 
319 For example:  getModelIndexByName(tree, "HYDRO", "NATURAL OBJECTS", "Immersible zone_1")
320 """ 
321 def getModelIndexByName(treeObj, *parentNames):
322     parentNodeName = parentNames[0].replace('_',"\\\\_")
323     waitForObjectItem(treeObj,  parentNodeName)
324     # clickItem(treeObj, parentNodeName, 5, 5, 0, Qt.LeftButton)
325     
326     root = treeObj.indexAt(QPoint(0,0))
327      
328     for name in parentNames[1:]:
329         idx = getChildModelIndex(root, name)
330         root = idx
331     return root    
332
333
334     
335 def getObjectBrowserItem(theItem, theParent=":HYDRO_QModelIndex", theOccurrence = 1):
336     return "{column='0' container='%s' occurrence='%s' text='%s' type='QModelIndex'}" % (theParent,  theOccurrence, theItem)  
337
338 def getItemText(item, parent):
339     if parent is None:
340         return item
341     else:
342         return "%s.%s" % (parent, item.replace('_',"\\\\_"))
343
344 def popupItem(*menuPath):
345     menu = waitForObject("{type='QtxMenu' unnamed='1' visible='1'}")
346     parent = "{type='QtxMenu' unnamed='1' visible='1'}"
347     for item in menuPath[:-1]:
348         test.log("Element",str(item)+" menu "+str(menu))
349         activateItem(waitForObjectItem(menu, item))
350         menu = "{title='%s' type='QMenu' unnamed='1' visible='1'}" % (item)
351         parent = menu
352     activateItem(waitForObjectItem(menu, menuPath[-1]))
353
354 def viewerPopupItem(menu_type, *menuPath ):
355     menu = waitForObject("{type='%s' unnamed='1' visible='1'}" % menu_type)
356         
357     for item_name in menuPath[:-1]:
358         menu_children = object.children(menu)
359         for child in menu_children:
360             properties = object.properties(child)
361             if properties.get("text", "") == item_name:
362                 mouseClick(child, 5, 5, 0, Qt.LeftButton)
363                 menu = child
364                 break
365             
366     activateItem(waitForObjectItem(menu, menuPath[-1]))
367
368 def activateViewerContextMenuItem(viewer, x, y, *menuPath): 
369     vtkViewer = waitForObject(viewer)
370     if x < 0:
371         x = vtkViewer.width/2
372     if y < 0:
373         y = vtkViewer.height/2
374     
375     mouseClick(vtkViewer, x, y, 0, Qt.LeftButton)
376     mouseClick(vtkViewer, x, y, 0, Qt.RightButton)
377     viewerPopupItem("QtxMenu", *menuPath)
378     res = waitFor("object.exists('%s')" % "{type=\\'QtxMenu\\' unnamed=\\'1\\' visible=\\'1\\'}",10000)
379     if res:
380         mouseClick(vtkViewer, x, y, 0, Qt.LeftButton)
381
382
383 def getFullItemName(itemIndex):
384     fullName = str(itemIndex.data().toString())
385     parentIndex = itemIndex.parent()
386     
387     while parentIndex.isValid():
388         parentName = str(parentIndex.data().toString())
389         fullName = "%s::%s" % (parentName, fullName) 
390         
391         parentIndex = parentIndex.parent()
392         
393     return fullName
394     
395 def getChildValues(parentIndex, theIsRecursive = True):
396     values = {}
397     row = 0
398     child_index0 = parentIndex.child(row, 0)
399     while child_index0.isValid():
400         child_index1 = child_index0.sibling(row, 1)
401         if child_index1.isValid():
402             key = getFullItemName(child_index0) # str(child_index0.data().toString())
403             value = str(child_index1.data().toString())
404             values[key] = value
405         
406         if theIsRecursive:
407             values.update(getChildValues(child_index0))
408             
409         row += 1
410         child_index0 = parentIndex.child(row, 0)
411         
412     return values 
413     
414 def getTreeValues(treeObj):
415     root = treeObj.indexAt(QPoint(0,0))
416     
417     return getChildValues(root)
418     
419 def checkContainsStringValues(values, stringKeys):
420     res = True
421     
422     for key in stringKeys:
423         if not values.has_key(key):
424             res = False
425             test.fatal("Map of values doesn't contain %s key" % key)
426         elif len(values[key]) < 1:
427             res = False
428             test.fatal("Value for key %s is empty" % key)
429             
430     return res
431      
432 def isInteger(value):
433     res = True
434     
435     intValue = cast(value, int)
436     res = intValue is not None
437         
438     return res
439
440 def isFloat(value):
441     res = True
442     
443     try:
444         float(value)
445     except ValueError:
446         res = False
447         
448     return res
449      
450 def checkContainsIntValues(values, intKeys):
451     res = True
452     
453     for key in intKeys:
454         if not values.has_key(key):
455             res = False
456             test.fatal("Map of values doesn't contain %s key" % key)
457         elif not isInteger(values[key]):
458             res = False
459             test.fatal("Value for key %s is not an integer ('%s')" % (key, values[key]))
460             
461     return res
462     
463 def checkContainsListOfIntValues(values, listOfIntKeys, sep):
464     res = True
465     
466     for key in listOfIntKeys:
467         if not values.has_key(key):
468             res = False
469             test.fatal("Map of values doesn't contain %s key" % key)
470         else:
471             listItems = values[key].split(sep)
472             
473             for item in listItems:
474                 if not isInteger(item):
475                     res = False
476                     test.fatal("Value for key %s is not a list of integer ('%s')" % (key, values[key]))
477             
478     return res
479     
480 def checkContainsFloatValues(values, floatKeys):
481     res = True
482     
483     for key in floatKeys:
484         if not values.has_key(key):
485             res = False
486             test.fatal("Map of values doesn't contain %s key" % key)
487         elif not isFloat(values[key]):
488             res = False
489             test.fatal("Value for key %s is not a float ('%s')" % (key, values[key]))
490             
491     return res
492     
493 """
494 Set the given value to the input field.
495 """
496 def setInputFieldValue(field, value):
497     type(field, "<Ctrl+A>")
498     type(field, value)
499     
500     
501 def clearSelection():
502     mouseClick(waitForObject(":SALOME *.3D View Operations_OCCViewer_ViewPort3d"), 1, 1, 0, Qt.LeftButton)
503
504 def getChildNames(tree, root):
505     row = 0
506     list=[]
507     rootName = str(root.data().toString())
508     while root.isValid():
509         rootName1 = str(root.data().toString())
510         child = root.child(0, 0)
511         if child.isValid():
512             childName = str(child.data().toString())
513             list.extend( getChildNames(tree, child) )
514         else:
515             if not tree.isRowHidden(row, root.parent()):
516                 name = getFullItemName(root)
517                 list.append(name)    
518         row += 1
519         root = root.sibling(row, 0)
520         
521     return list
522
523 def getTreeNames(tree):
524     root = tree.indexAt(QPoint(0,0))
525     return getChildNames( tree, root)
526
527
528