Salome HOME
Corrections of examples path after install with scbi
[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 as 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     #@MZN clickButton(waitForObject(":SALOME *.Fit All_QToolButton"))
213     btn = waitForObject(":SALOME *.Fit All_QToolButton")
214     btn.click()
215
216 """
217 Click "Reset" button
218 """ 
219 def resetOCCViewer():
220     clickButton(waitForObject(":SALOME *.Reset_QToolButton"))
221
222 """
223 Show/Hide trihedron axis in OCC Viewer
224 """
225 def showTrihedron(val):
226     btn = waitForObject(":SALOME *.Show/Hide trihedron_QToolButton")
227     if btn.checked != val:
228         clickButton(btn)
229 """
230 Call Transparency popup menu in OCC Viewer
231 """
232 def setOCCViwerTransparency(value, pos_x = -1, pos_y = -1 ):
233     setTransparency(":SALOME *.3D View Operations_OCCViewer_ViewPort3d", value, pos_x, pos_y)
234     
235 """
236 Call Isos popup menu in OCC Viewer
237 """
238 def setOCCViwerIsos(u, v, pos_x = -1, pos_y = -1):
239     setIsos(":SALOME *.3D View Operations_OCCViewer_ViewPort3d", u, v, pos_x, pos_y)
240
241 """
242 Mouse click in OCC viewer.
243 """
244 def occMouseClick(x, y):
245     mouseClick(waitForObject(":SALOME *.3D View Operations_OCCViewer_ViewPort3d"), x, y, 0, Qt.LeftButton)
246     
247 """
248 Multiple mouse clicks in OCC viewer.
249 """
250 def occMouseClicks(points):
251     occViewer = waitForObject(":SALOME *.3D View Operations_OCCViewer_ViewPort3d")
252     for pnt in points:
253         mouseClick(occViewer, pnt[0], pnt[1], 0, Qt.LeftButton)
254     
255 """
256 Mouse drag in OCC viewer.
257 """
258 def occMouseDrag(x1, y1, x2, y2):
259     mouseDrag(waitForObject(":SALOME *.3D View Operations_OCCViewer_ViewPort3d"), x1, y1, x2, y2, 1, Qt.LeftButton)
260
261 #--------------------------------------------------------------------------
262 # VTK Viewer
263 #--------------------------------------------------------------------------
264     
265 """
266 Activate context menu item at the given point of VTK viewer.
267 For example:  activateVTKContextMenuItem(50, 100, "Hide")
268 """
269 def activateVTKContextMenuItem(x, y, *menuPath):
270     activateViewerContextMenuItem(":SALOME *.SVTK_RenderWindowInteractor_SVTK_RenderWindowInteractor", x, y, *menuPath)
271
272 def setVTKIsos(u, v, pos_x = -1, pos_y = -1):
273     setIsos(":SALOME *.SVTK_RenderWindowInteractor_SVTK_RenderWindowInteractor", u, v, pos_x, pos_y)
274
275 def setVTKTransparency(value, pos_x = -1, pos_y = -1 ):
276     setTransparency(":SALOME *.SVTK_RenderWindowInteractor_SVTK_RenderWindowInteractor", value, pos_x, pos_y)
277     
278
279 #--------------------------------------------------------------------------
280 # Widgets
281 #--------------------------------------------------------------------------
282 """
283 Set button checked or unchecked
284 """
285 def setButtonChecked(button, isChecked):
286     if (isChecked != button.checked):
287         clickButton(button)
288
289     test.verify(button.checked == isChecked)
290
291 """
292 Select item with the given text in the combo box
293 """
294 def selectComboBoxItem(combo, itemText):
295     for index in range(combo.count):
296         if combo.itemText(index) == itemText:
297             combo.setCurrentIndex(index)
298             break
299         
300     test.verify(combo.currentText == itemText)
301     pass
302
303 """
304 Check that the combo box contains only the given items.
305 """
306 def checkComboBoxContent(combo, items):
307     sortItems = list(items)
308     sortItems.sort()
309     
310     comboItems = []
311     for index in range(combo.count):
312         comboItems.append(str(combo.itemText(index)))
313     
314     comboItems.sort()
315         
316     test.compare(comboItems, sortItems)
317     pass
318
319 """
320 Click the object item.
321 """
322 def clickObjectItem(objectName, itemName, modifier=0):
323     itemNameFormatted = itemName.replace('_',"\\\\_")
324     waitForObjectItem(objectName, itemNameFormatted)
325     clickItem(objectName, itemNameFormatted, 10, 5, modifier, Qt.LeftButton)
326     
327 """
328 Double click the object item.
329 """
330 def doubleClickObjectItem(objectName, itemName):
331     itemNameFormatted = itemName.replace('_',"\\\\_")
332     waitForObjectItem(objectName, itemNameFormatted)
333     doubleClickItem(objectName, itemNameFormatted, 10, 5, 0, Qt.LeftButton)
334     
335 #--------------------------------------------------------------------------
336 # Internal methods
337 #--------------------------------------------------------------------------
338
339 """
340 Returns the QModelIndex for child with given name and parent index
341 Warning: may works incorrectly for items with duplicated names   
342 """    
343 def getChildModelIndex(parentIdx, name):
344     row=0
345     if parentIdx is None:
346         return None
347     childIdx = parentIdx.child(row, 0)
348     while childIdx.isValid():
349         if name == str(childIdx.data().toString()):
350             return childIdx
351         row += 1
352         childIdx = childIdx.sibling(row, 0)
353     return None    
354
355 """
356 Returns the QModelIndex form given tree by list of hierarchical names 
357 For example:  getModelIndexByName(tree, "HYDRO", "NATURAL OBJECTS", "Immersible zone_1")
358 """ 
359 def getModelIndexByName(treeObj, *parentNames):
360     parentNodeName = parentNames[0].replace('_',"\\\\_")
361     waitForObjectItem(treeObj,  parentNodeName)
362     # clickItem(treeObj, parentNodeName, 5, 5, 0, Qt.LeftButton)
363     
364     root = treeObj.indexAt(QPoint(0,0))
365      
366     for name in parentNames[1:]:
367         idx = getChildModelIndex(root, name)
368         root = idx
369     return root    
370
371
372     
373 def getObjectBrowserItem(theItem, theParent=":HYDRO_QModelIndex", theOccurrence = 1):
374     return "{column='0' container='%s' occurrence='%s' text='%s' type='QModelIndex'}" % (theParent,  theOccurrence, theItem)  
375
376 def getItemText(item, parent):
377     if parent is None:
378         return item
379     else:
380         return "%s.%s" % (parent, item.replace('_',"\\\\_"))
381
382 def popupItem(*menuPath):
383     menu = waitForObject("{type='QtxMenu' unnamed='1' visible='1'}")
384     parent = "{type='QtxMenu' unnamed='1' visible='1'}"
385     for item in menuPath[:-1]:
386         test.log("Element",str(item)+" menu "+str(menu))
387         activateItem(waitForObjectItem(menu, item))
388         menu = "{title='%s' type='QMenu' unnamed='1' visible='1'}" % (item)
389         parent = menu
390     activateItem(waitForObjectItem(menu, menuPath[-1]))
391
392 def viewerPopupItem(menu_type, *menuPath ):
393     menu = waitForObject("{type='%s' unnamed='1' visible='1'}" % menu_type)
394         
395     for item_name in menuPath[:-1]:
396         menu_children = object.children(menu)
397         for child in menu_children:
398             properties = object.properties(child)
399             if properties.get("text", "") == item_name:
400                 mouseClick(child, 5, 5, 0, Qt.LeftButton)
401                 menu = child
402                 break
403             
404     activateItem(waitForObjectItem(menu, menuPath[-1]))
405
406 def activateViewerContextMenuItem(viewer, x, y, *menuPath): 
407     vtkViewer = waitForObject(viewer)
408     if x < 0:
409         x = vtkViewer.width/2
410     if y < 0:
411         y = vtkViewer.height/2
412     
413     mouseClick(vtkViewer, x, y, 0, Qt.LeftButton)
414     mouseClick(vtkViewer, x, y, 0, Qt.RightButton)
415     viewerPopupItem("QtxMenu", *menuPath)
416     res = waitFor("object.exists('%s')" % "{type=\\'QtxMenu\\' unnamed=\\'1\\' visible=\\'1\\'}",10000)
417     if res:
418         mouseClick(vtkViewer, x, y, 0, Qt.LeftButton)
419
420
421 def getFullItemName(itemIndex):
422     fullName = str(itemIndex.data().toString())
423     parentIndex = itemIndex.parent()
424     
425     while parentIndex.isValid():
426         parentName = str(parentIndex.data().toString())
427         fullName = "%s::%s" % (parentName, fullName) 
428         
429         parentIndex = parentIndex.parent()
430         
431     return fullName
432     
433 def getChildValues(parentIndex, theIsRecursive = True):
434     values = {}
435     row = 0
436     child_index0 = parentIndex.child(row, 0)
437     while child_index0.isValid():
438         child_index1 = child_index0.sibling(row, 1)
439         if child_index1.isValid():
440             key = getFullItemName(child_index0) # str(child_index0.data().toString())
441             value = str(child_index1.data().toString())
442             values[key] = value
443         
444         if theIsRecursive:
445             values.update(getChildValues(child_index0))
446             
447         row += 1
448         child_index0 = parentIndex.child(row, 0)
449         
450     return values 
451     
452 def getTreeValues(treeObj):
453     root = treeObj.indexAt(QPoint(0,0))
454     
455     return getChildValues(root)
456     
457 def checkContainsStringValues(values, stringKeys):
458     res = True
459     
460     for key in stringKeys:
461         if key not in values:
462             res = False
463             test.fatal("Map of values doesn't contain %s key" % key)
464         elif len(values[key]) < 1:
465             res = False
466             test.fatal("Value for key %s is empty" % key)
467             
468     return res
469      
470 def isInteger(value):
471     res = True
472     
473     intValue = cast(value, int)
474     res = intValue is not None
475         
476     return res
477
478 def isFloat(value):
479     res = True
480     
481     try:
482         float(value)
483     except ValueError:
484         res = False
485         
486     return res
487      
488 def checkContainsIntValues(values, intKeys):
489     res = True
490     
491     for key in intKeys:
492         if key not in values:
493             res = False
494             test.fatal("Map of values doesn't contain %s key" % key)
495         elif not isInteger(values[key]):
496             res = False
497             test.fatal("Value for key %s is not an integer ('%s')" % (key, values[key]))
498             
499     return res
500     
501 def checkContainsListOfIntValues(values, listOfIntKeys, sep):
502     res = True
503     
504     for key in listOfIntKeys:
505         if key not in values:
506             res = False
507             test.fatal("Map of values doesn't contain %s key" % key)
508         else:
509             listItems = values[key].split(sep)
510             
511             for item in listItems:
512                 if not isInteger(item):
513                     res = False
514                     test.fatal("Value for key %s is not a list of integer ('%s')" % (key, values[key]))
515             
516     return res
517     
518 def checkContainsFloatValues(values, floatKeys):
519     res = True
520     
521     for key in floatKeys:
522         if key not in values:
523             res = False
524             test.fatal("Map of values doesn't contain %s key" % key)
525         elif not isFloat(values[key]):
526             res = False
527             test.fatal("Value for key %s is not a float ('%s')" % (key, values[key]))
528             
529     return res
530     
531 """
532 Set the given value to the input field.
533 """
534 def setInputFieldValue(field, value):
535     type(field, "<Ctrl+A>")
536     type(field, value)
537     
538     
539 def clearSelection():
540     mouseClick(waitForObject(":SALOME *.3D View Operations_OCCViewer_ViewPort3d"), 1, 1, 0, Qt.LeftButton)
541
542 def getChildNames(tree, root):
543     row = 0
544     list=[]
545     rootName = str(root.data().toString())
546     while root.isValid():
547         rootName1 = str(root.data().toString())
548         child = root.child(0, 0)
549         if child.isValid():
550             childName = str(child.data().toString())
551             list.extend( getChildNames(tree, child) )
552         else:
553             if not tree.isRowHidden(row, root.parent()):
554                 name = getFullItemName(root)
555                 list.append(name)    
556         row += 1
557         root = root.sibling(row, 0)
558         
559     return list
560
561 def getTreeNames(tree):
562     root = tree.indexAt(QPoint(0,0))
563     return getChildNames( tree, root)
564
565
566