utils.py 32.7 KB
Newer Older
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
#############################################################################
##
## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
## Contact: http://www.qt-project.org/legal
##
## This file is part of Qt Creator.
##
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and Digia.  For licensing terms and
## conditions see http://qt.digia.com/licensing.  For further information
## use the contact form at http://qt.digia.com/contact-us.
##
## GNU Lesser General Public License Usage
## Alternatively, this file may be used under the terms of the GNU Lesser
## General Public License version 2.1 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU Lesser General Public License version 2.1 requirements
## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
##
## In addition, as a special exception, Digia gives you certain additional
## rights.  These rights are described in the Digia Qt LGPL Exception
## version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
##
#############################################################################

30
import tempfile
31

32
33
def neededFilePresent(path):
    found = os.path.exists(path)
34
35
36
    if os.getenv("SYSTEST_DEBUG") == "1":
        checkAccess(path)
    elif not found:
37
38
39
        test.fatal("Missing file or directory: " + path)
    return found

40
def tempDir():
41
42
43
44
    Result = os.path.abspath(os.getcwd()+"/../../testing")
    if not os.path.exists(Result):
        os.mkdir(Result)
    return tempfile.mkdtemp(prefix="qtcreator_", dir=Result)
45
46
47
48
49

def deleteDirIfExists(path):
    shutil.rmtree(path, True)

def verifyChecked(objectName):
50
    object = waitForObject(objectName)
51
52
53
    test.compare(object.checked, True)
    return object

54
55
def ensureChecked(objectName, shouldBeChecked = True, timeout=20000):
    object = waitForObject(objectName, timeout)
56
57
    # synchronize to avoid false positives
    waitFor('object.checked == shouldBeChecked', 1000)
58
59
    if object.checked ^ shouldBeChecked:
        clickButton(object)
60
61
62
63
    if shouldBeChecked:
        state = "checked"
    else:
        state = "unchecked"
64
65
    test.log("New state for QCheckBox: %s" % state,
             str(objectName))
Robert Loehning's avatar
Robert Loehning committed
66
    test.verify(waitFor("object.checked == shouldBeChecked", 1000))
67
68
    return object

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# verify that an object is in an expected enable state. Returns the object.
# param objectSpec  specifies the object to check. It can either be a string determining an object
#                   or the object itself. If it is an object, it must exist already.
# param expectedState is the expected enable state of the object
def verifyEnabled(objectSpec, expectedState = True):
    if isinstance(objectSpec, (str, unicode)):
        waitFor("object.exists('" + objectSpec + "')", 20000)
        foundObject = findObject(objectSpec)
    else:
        foundObject = objectSpec
    if objectSpec == None:
        test.warning("No valid object in function verifyEnabled.")
    else:
        test.compare(foundObject.enabled, expectedState)
    return foundObject
84

85
86
87
88
# select an item from a combo box
# param objectSpec  specifies the combo box. It can either be a string determining an object
#                   or the object itself. If it is an object, it must exist already.
# param itemName is the item to be selected in the combo box
89
# returns True if selection was changed or False if the wanted value was already selected
90
91
def selectFromCombo(objectSpec, itemName):
    object = verifyEnabled(objectSpec)
92
93
94
    if itemName == str(object.currentText):
        return False
    else:
95
96
        mouseClick(object, 5, 5, 0, Qt.LeftButton)
        mouseClick(waitForObjectItem(object, itemName.replace(".", "\\.")), 5, 5, 0, Qt.LeftButton)
97
98
        test.verify(waitFor("str(object.currentText)==itemName", 5000),
                    "Switched combo item to '%s'" % itemName)
99
        return True
100

101
102
103
def selectFromLocator(filter, itemName = None):
    if itemName == None:
        itemName = filter
104
    itemName = itemName.replace(".", "\\.").replace("_", "\\_")
105
    locator = waitForObject(":*Qt Creator_Utils::FilterLineEdit")
106
107
108
109
110
111
112
113
    mouseClick(locator, 5, 5, 0, Qt.LeftButton)
    replaceEditorContent(locator, filter)
    # clicking the wanted item
    # if you replace this by pressing ENTER, be sure that something is selected
    # otherwise you will run into unwanted behavior
    wantedItem = waitForObjectItem("{type='QTreeView' unnamed='1' visible='1'}", itemName)
    doubleClick(wantedItem, 5, 5, 0, Qt.LeftButton)

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def wordUnderCursor(window):
    cursor = window.textCursor()
    oldposition = cursor.position()
    cursor.movePosition(QTextCursor.StartOfWord)
    cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor)
    returnValue = cursor.selectedText()
    cursor.setPosition(oldposition)
    return returnValue

def lineUnderCursor(window):
    cursor = window.textCursor()
    oldposition = cursor.position()
    cursor.movePosition(QTextCursor.StartOfLine)
    cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)
    returnValue = cursor.selectedText()
    cursor.setPosition(oldposition)
    return returnValue

def which(program):
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK)

136
137
138
    def callableFile(path):
        if is_exe(path):
            return path
139
        if platform.system() in ('Windows', 'Microsoft'):
140
141
142
143
            for suffix in suffixes.split(os.pathsep):
                if is_exe(path + suffix):
                    return path + suffix
        return None
144

145
146
147
148
149
150
151
152
153
    if platform.system() in ('Windows', 'Microsoft'):
        suffixes = os.getenv("PATHEXT")
        if not suffixes:
            test.fatal("Can't read environment variable PATHEXT. Please check your installation.")
            suffixes = ""

    fpath, fname = os.path.split(program)
    if fpath:
        return callableFile(program)
154
    else:
155
156
157
158
        if platform.system() in ('Windows', 'Microsoft'):
            cf = callableFile(os.getcwd() + os.sep + program)
            if cf:
                return cf
159
160
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
161
162
163
164
            cf = callableFile(exe_file)
            if cf:
                return cf
        return None
165

Bill King's avatar
Bill King committed
166
167
signalObjects = {}

168
# do not call this function directly - it's only a helper
169
def __callbackFunction__(object, *args):
Bill King's avatar
Bill King committed
170
    global signalObjects
171
#    test.log("__callbackFunction__: "+objectMap.realName(object))
Bill King's avatar
Bill King committed
172
173
174
    signalObjects[objectMap.realName(object)] += 1

def waitForSignal(object, signal, timeout=30000):
175
176
177
178
179
    global signalObjects
    realName = prepareForSignal(object, signal)
    beforeCount = signalObjects[realName]
    waitFor("signalObjects[realName] > beforeCount", timeout)

180
181
handledSignal = {}

182
def prepareForSignal(object, signal):
Bill King's avatar
Bill King committed
183
    global signalObjects
184
    global handledSignal
Bill King's avatar
Bill King committed
185
186
187
    overrideInstallLazySignalHandler()
    realName = objectMap.realName(object)
#    test.log("waitForSignal: "+realName)
188
189
190
191
192
193
194
195
196
197
    if realName in handledSignal.keys():
        if handledSignal[realName] != signal:
            # The current implementation does not support this.
            # When an object has two different handled signals, waitForSignal() will only wait
            # for the first of them to be emitted.
            test.warning("You are trying to handle two different signals from the same object.",
                         "Adding %s to object %s, which already has handled signal %s. "
                         "This can lead to unexpected results." % (signal, realName, handledSignal[realName]))
    else:
        handledSignal[realName] = signal
Bill King's avatar
Bill King committed
198
199
    if not (realName in signalObjects):
        signalObjects[realName] = 0
200
201
    installLazySignalHandler(object, signal, "__callbackFunction__")
    return realName
202

203
204
205
206
207
208
209
# this function removes the user files of given pro file(s)
# can be called with a single string object or a list of strings holding path(s) to
# the pro file(s) returns False if it could not remove all user files or has been
# called with an unsupported object
def cleanUpUserFiles(pathsToProFiles=None):
    if pathsToProFiles==None:
        return False
210
    if isinstance(pathsToProFiles, (str, unicode)):
211
        filelist = glob.glob(pathsToProFiles+".user*")
212
    elif isinstance(pathsToProFiles, (list, tuple)):
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
        filelist = []
        for p in pathsToProFiles:
            filelist.extend(glob.glob(p+".user*"))
    else:
        test.fatal("Got an unsupported object.")
        return False
    doneWithoutErrors = True
    for file in filelist:
        try:
            file = os.path.abspath(file)
            os.remove(file)
        except:
            doneWithoutErrors = False
    return doneWithoutErrors

228
def invokeMenuItem(menu, item, *subItems):
229
230
231
232
233
    if platform.system() == "Darwin":
        try:
            waitForObject(":Qt Creator.QtCreator.MenuBar_QMenuBar", 2000)
        except:
            nativeMouseClick(waitForObject(":Qt Creator_Core::Internal::MainWindow", 1000), 20, 20, 0, Qt.LeftButton)
Christian Stenger's avatar
Christian Stenger committed
234
    menuObject = waitForObjectItem(":Qt Creator.QtCreator.MenuBar_QMenuBar", menu)
235
    waitFor("menuObject.visible", 1000)
236
    activateItem(menuObject)
237
    itemObject = waitForObjectItem(objectMap.realName(menuObject), item)
238
    waitFor("itemObject.enabled", 2000)
239
    activateItem(itemObject)
240
    for subItem in subItems:
Christian Stenger's avatar
Christian Stenger committed
241
242
        sub = itemObject.menu()
        waitFor("sub.visible", 1000)
243
244
        itemObject = waitForObjectItem(sub, subItem)
        activateItem(itemObject)
245
246
247

def logApplicationOutput():
    # make sure application output is shown
248
    ensureChecked(":Qt Creator_AppOutput_Core::Internal::OutputPaneToggleButton")
249
    try:
250
        output = waitForObject("{type='Core::OutputWindow' visible='1' windowTitle='Application Output Window'}")
251
        test.log("Application Output:\n%s" % output.plainText)
252
        return str(output.plainText)
253
254
    except:
        test.fail("Could not find any Application Output - did the project run?")
255
        return None
256
257
258
259
260
261
262

# get the output from a given cmdline call
def getOutputFromCmdline(cmdline):
    versCall = subprocess.Popen(cmdline, stdout=subprocess.PIPE, shell=True)
    result = versCall.communicate()[0]
    versCall.stdout.close()
    return result
Christian Stenger's avatar
Christian Stenger committed
263

264
def selectFromFileDialog(fileName, waitForFile=False):
265
266
267
268
269
270
271
    if platform.system() == "Darwin":
        snooze(1)
        nativeType("<Command+Shift+g>")
        snooze(1)
        nativeType(fileName)
        snooze(1)
        nativeType("<Return>")
272
        snooze(3)
273
        nativeType("<Return>")
274
        snooze(1)
275
    else:
276
        fName = os.path.basename(os.path.abspath(fileName))
277
        pName = os.path.dirname(os.path.abspath(fileName)) + os.sep
278
279
        waitForObject("{name='QFileDialog' type='QFileDialog' visible='1'}")
        pathLine = waitForObject("{name='fileNameEdit' type='QLineEdit' visible='1'}")
280
        snooze(1)
281
        replaceEditorContent(pathLine, pName)
282
        clickButton(waitForObject("{text='Open' type='QPushButton'}"))
283
        waitFor("str(pathLine.text)==''")
284
        snooze(1)
285
        replaceEditorContent(pathLine, fName)
286
        clickButton(waitForObject("{text='Open' type='QPushButton'}"))
287
288
    if waitForFile:
        fileCombo = waitForObject(":Qt Creator_FilenameQComboBox")
289
290
        if not waitFor("str(fileCombo.currentText) in fileName", 5000):
            test.fail("%s could not be opened in time." % fileName)
291

Christian Stenger's avatar
Christian Stenger committed
292
293
294
# add Qt documentations from given paths
# param which a list/tuple of the paths to the qch files to be added
def addHelpDocumentation(which):
Christian Stenger's avatar
Christian Stenger committed
295
296
297
298
299
    global sdkPath
    invokeMenuItem("Tools", "Options...")
    waitForObjectItem(":Options_QListView", "Help")
    clickItem(":Options_QListView", "Help", 14, 15, 0, Qt.LeftButton)
    waitForObject("{container=':Options.qt_tabwidget_tabbar_QTabBar' type='TabItem' text='Documentation'}")
300
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Documentation")
Christian Stenger's avatar
Christian Stenger committed
301
302
    # get rid of all docs already registered
    listWidget = waitForObject("{type='QListWidget' name='docsListWidget' visible='1'}")
303
    if listWidget.count > 0:
Christian Stenger's avatar
Christian Stenger committed
304
305
        rect = listWidget.visualItemRect(listWidget.item(0))
        mouseClick(listWidget, rect.x+5, rect.y+5, 0, Qt.LeftButton)
306
        type(listWidget, "<Ctrl+A>")
Christian Stenger's avatar
Christian Stenger committed
307
        mouseClick(waitForObject("{type='QPushButton' name='removeButton' visible='1'}"), 5, 5, 0, Qt.LeftButton)
Christian Stenger's avatar
Christian Stenger committed
308
309
310
    for qch in which:
        clickButton(waitForObject("{type='QPushButton' name='addButton' visible='1' text='Add...'}"))
        selectFromFileDialog(qch)
Christian Stenger's avatar
Christian Stenger committed
311
    clickButton(waitForObject(":Options.OK_QPushButton"))
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
def addCurrentCreatorDocumentation():
    currentCreatorPath = currentApplicationContext().cwd
    if platform.system() == "Darwin":
        docPath = os.path.abspath(os.path.join(currentCreatorPath, "Qt Creator.app", "Contents",
                                               "Resources", "doc", "qtcreator.qch"))
    else:
        docPath = os.path.abspath(os.path.join(currentCreatorPath, "..", "share", "doc",
                                               "qtcreator", "qtcreator.qch"))
    if not os.path.exists(docPath):
        test.fatal("Missing current Qt Creator documentation (expected in %s)" % docPath)
        return
    invokeMenuItem("Tools", "Options...")
    waitForObjectItem(":Options_QListView", "Help")
    clickItem(":Options_QListView", "Help", 14, 15, 0, Qt.LeftButton)
    waitForObject("{container=':Options.qt_tabwidget_tabbar_QTabBar' type='TabItem' text='Documentation'}")
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Documentation")
    clickButton(waitForObject("{type='QPushButton' name='addButton' visible='1' text='Add...'}"))
    selectFromFileDialog(docPath)
    try:
        waitForObject("{type='QMessageBox' unnamed='1' visible='1' "
                      "text?='Unable to register documentation.*'}", 3000)
        test.passes("Qt Creator's documentation found already registered.")
        clickButton(waitForObject("{type='QPushButton' text='OK' unnamed='1' visible='1' "
                                  "container={name='groupBox' type='QGroupBox' visible='1'}}"))
    except:
        test.fail("Added Qt Creator's documentation explicitly.")
    clickButton(waitForObject(":Options.OK_QPushButton"))

341
342
343
344
345
346
def verifyOutput(string, substring, outputFrom, outputIn):
    index = string.find(substring)
    if (index == -1):
        test.fail("Output from " + outputFrom + " could not be found in " + outputIn)
    else:
        test.passes("Output from " + outputFrom + " found at position " + str(index) + " of " + outputIn)
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

# function that verifies the existance and the read permissions
# of the given file path
# if the executing user hasn't the read permission it checks
# the parent folders for their execute permission
def checkAccess(pathToFile):
    if os.path.exists(pathToFile):
        test.log("Path '%s' exists" % pathToFile)
        if os.access(pathToFile, os.R_OK):
            test.log("Got read access on '%s'" % pathToFile)
        else:
            test.fail("No read permission on '%s'" % pathToFile)
    else:
        test.fatal("Path '%s' does not exist or cannot be accessed" % pathToFile)
        __checkParentAccess__(pathToFile)

# helper function for checking the execute rights of all
# parents of filePath
def __checkParentAccess__(filePath):
    for i in range(1, filePath.count(os.sep)):
        tmp = filePath.rsplit(os.sep, i)[0]
        if os.access(tmp, os.X_OK):
            test.log("Got execute permission on '%s'" % tmp)
        else:
            test.fail("No execute permission on '%s'" % tmp)
372
373

# this function checks for all configured Qt versions inside
374
375
# options dialog and returns a dict holding the kits as keys
# and a list of information of its configured Qt
376
def getConfiguredKits(isMaddeDisabled=True):
377
378
379
    def __retrieveQtVersionName__(target, version):
        treeWidget = waitForObject(":QtSupport__Internal__QtVersionManager.qtdirList_QTreeWidget")
        return treeWidget.currentItem().text(0)
380
381
    # end of internal function for iterateQtVersions
    def __setQtVersionForKit__(kit, kitName, kitsQtVersionName):
382
        treeView = waitForObject(":Kits_Or_Compilers_QTreeView")
383
384
385
386
387
388
        clickItem(treeView, kit, 5, 5, 0, Qt.LeftButton)
        qtVersionStr = str(waitForObject(":Kits_QtVersion_QComboBox").currentText)
        kitsQtVersionName[kitName] = qtVersionStr
    # end of internal function for iterate kits

    kitsWithQtVersionName = {}
389
    result = {}
390
391
392
393
    # collect kits and their Qt versions
    targetsQtVersions, qtVersionNames = iterateQtVersions(True, False, __retrieveQtVersionName__)
    # update collected Qt versions with their configured device and version
    iterateKits(True, True, __setQtVersionForKit__, kitsWithQtVersionName)
394
    # merge defined target names with their configured Qt versions and devices
395
396
    for kit, qtVersion in kitsWithQtVersionName.iteritems():
        if isMaddeDisabled and kit in ('Fremantle', 'Harmattan') and qtVersion == 'None':
397
398
                test.log("Found Kit '%s' with unassigned Qt version (disabled Madde plugin)" % kit)
        elif qtVersion in qtVersionNames:
399
400
401
402
            result[kit] = targetsQtVersions[qtVersionNames.index(qtVersion)].items()[0]
        else:
            test.fail("Qt version '%s' for kit '%s' can't be found in qtVersionNames."
                      % (qtVersion, kit))
403
404
405
406
407
    clickButton(waitForObject(":Options.Cancel_QPushButton"))
    # adjust device name(s) to match getStringForTarget() - some differ from time to time
    for targetName in result.keys():
        targetInfo = result[targetName]
        if targetInfo[0] == "Maemo":
408
            result.update({targetName:
Christian Stenger's avatar
Christian Stenger committed
409
                           (Targets.getStringForTarget(Targets.MAEMO5), targetInfo[1])})
410
    test.log("Configured kits: %s" % str(result))
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    return result

def visibleCheckBoxExists(text):
    try:
        findObject("{type='QCheckBox' text='%s' visible='1'}" % text)
        return True
    except:
        return False

# this function verifies if the text matches the given
# regex inside expectedTexts
# param text must be a single str/unicode
# param expectedTexts can be str/unicode/list/tuple
def regexVerify(text, expectedTexts):
    if isinstance(expectedTexts, (str,unicode)):
        expectedTexts = [expectedTexts]
    for curr in expectedTexts:
        pattern = re.compile(curr)
        if pattern.match(text):
            return True
    return False

433
434
def checkDebuggingLibrary(kitIDs):
    def __getQtVersionForKit__(kit, kitName):
435
        treeView = waitForObject(":Kits_Or_Compilers_QTreeView")
436
437
438
439
        clickItem(treeView, kit, 5, 5, 0, Qt.LeftButton)
        return str(waitForObject(":Kits_QtVersion_QComboBox").currentText)
    # end of internal function for iterate kits

440
    # internal function to execute while iterating Qt versions
441
    def __checkDebugLibsInternalFunc__(target, version, kitStrings):
442
443
444
445
446
        built = failed = 0
        container = ("container=':qt_tabwidget_stackedwidget.QtSupport__Internal__"
                     "QtVersionManager_QtSupport::Internal::QtOptionsPageWidget'")
        buildLogWindow = ("window={name='QtSupport__Internal__ShowBuildLog' type='QDialog' "
                          "visible='1' windowTitle?='Debugging Helper Build Log*'}")
447
448
        treeWidget = waitForObject(":QtSupport__Internal__QtVersionManager.qtdirList_QTreeWidget")
        if str(treeWidget.currentItem().text(0)) in kitStrings.values():
449
            detailsButton = waitForObject("{%s type='Utils::DetailsButton' text='Details' "
450
                                          "visible='1' unnamed='1' occurrence='2'}" % container)
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
            ensureChecked(detailsButton)
            gdbHelperStat = waitForObject("{%s type='QLabel' name='gdbHelperStatus' "
                                          "visible='1'}" % container)
            if 'Not yet built.' in str(gdbHelperStat.text):
                clickButton(waitForObject("{%s type='QPushButton' name='gdbHelperBuildButton' "
                                          "text='Build' visible='1'}" % container))
                buildLog = waitForObject("{type='QPlainTextEdit' name='log' visible='1' %s}" % buildLogWindow)
                if str(buildLog.plainText).endswith('Build succeeded.'):
                    built += 1
                else:
                    failed += 1
                    test.fail("Building GDB Helper failed",
                              buildLog.plainText)
                clickButton(waitForObject("{type='QPushButton' text='Close' unnamed='1' "
                                          "visible='1' %s}" % buildLogWindow))
            else:
                built += 1
            ensureChecked(detailsButton, False)
        return (built, failed)
470
471
472
    # end of internal function for iterateQtVersions
    kits, qtv = iterateKits(True, False, __getQtVersionForKit__)
    qtVersionsOfKits = zip(kits, qtv)
Christian Stenger's avatar
Christian Stenger committed
473
    wantedKits = Targets.getTargetsAsStrings(kitIDs)
474
475
    kitsQtV = dict([i for i in qtVersionsOfKits if i[0] in wantedKits])
    tv, builtAndFailedList = iterateQtVersions(False, True, __checkDebugLibsInternalFunc__, kitsQtV)
476
477
478
479
480
481
482
483
484
485
    built = failed = 0
    for current in builtAndFailedList:
        if current[0]:
            built += current[0]
        if current[1]:
            failed += current[1]
    if failed > 0:
        test.fail("%d of %d GDB Helper compilations failed." % (failed, failed+built))
    else:
        test.passes("%d GDB Helper found compiled or successfully built." % built)
486
487
488
489
    if built == len(kitIDs):
        test.log("Function executed for all given kits.")
    else:
        test.fatal("Something's wrong - function has skipped some kits.")
490
491
492
493
494
    return failed == 0

# function that opens Options Dialog and parses the configured Qt versions
# param keepOptionsOpen set to True if the Options dialog should stay open when
#       leaving this function
495
496
# param alreadyOnOptionsDialog set to True if you already have opened the Options Dialog
#       (if False this function will open it via the MenuBar -> Tools -> Options...)
497
# param additionalFunction pass a function or name of a defined function to execute
498
499
#       for each correctly configured item on the list of Qt versions
#       (Qt versions having no assigned toolchain, failing qmake,... will be skipped)
500
501
502
503
504
505
506
507
508
509
510
511
#       this function must take at least 2 parameters - the first is the target name
#       and the second the version of the current selected Qt version item
# param argsForAdditionalFunc you can specify as much parameters as you want to pass
#       to additionalFunction from the outside
# the function returns a list of dict holding target-version mappings if used without
# additionalFunction
# WATCH OUT! if you're using the additionalFunction parameter - this function will
# return the list mentioned above as well as the returned value(s) from
# additionalFunction. You MUST call this function like
# result, additionalResult = _iterateQtVersions(...)
# where additionalResult is the result of all executions of additionalFunction which
# means it is a list of results.
512
513
def iterateQtVersions(keepOptionsOpen=False, alreadyOnOptionsDialog=False,
                      additionalFunction=None, *argsForAdditionalFunc):
514
515
    result = []
    additionalResult = []
516
517
    if not alreadyOnOptionsDialog:
        invokeMenuItem("Tools", "Options...")
518
519
    waitForObjectItem(":Options_QListView", "Build & Run")
    clickItem(":Options_QListView", "Build & Run", 14, 15, 0, Qt.LeftButton)
520
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Qt Versions")
521
522
523
    pattern = re.compile("Qt version (?P<version>.*?) for (?P<target>.*)")
    treeWidget = waitForObject(":QtSupport__Internal__QtVersionManager.qtdirList_QTreeWidget")
    root = treeWidget.invisibleRootItem()
524
    for rootChild in dumpChildren(root):
525
        rootChildText = str(rootChild.text(0)).replace(".", "\\.").replace("_", "\\_")
526
        for subChild in dumpChildren(rootChild):
527
            subChildText = str(subChild.text(0)).replace(".", "\\.").replace("_", "\\_")
528
529
530
531
            clickItem(treeWidget, ".".join([rootChildText,subChildText]), 5, 5, 0, Qt.LeftButton)
            currentText = str(waitForObject(":QtSupport__Internal__QtVersionManager.QLabel").text)
            matches = pattern.match(currentText)
            if matches:
532
533
                target = matches.group("target").strip()
                version = matches.group("version").strip()
534
                result.append({target:version})
535
536
537
538
539
540
541
542
543
544
545
546
547
                if additionalFunction:
                    try:
                        if isinstance(additionalFunction, (str, unicode)):
                            currResult = globals()[additionalFunction](target, version, *argsForAdditionalFunc)
                        else:
                            currResult = additionalFunction(target, version, *argsForAdditionalFunc)
                    except:
                        import sys
                        t,v,tb = sys.exc_info()
                        currResult = None
                        test.fatal("Function to additionally execute on Options Dialog could not be found or "
                                   "an exception occured while executing it.", "%s(%s)" % (str(t), str(v)))
                    additionalResult.append(currResult)
548
    if not keepOptionsOpen:
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
        clickButton(waitForObject(":Options.Cancel_QPushButton"))
    if additionalFunction:
        return result, additionalResult
    else:
        return result

# function that opens Options Dialog (if necessary) and parses the configured Kits
# param keepOptionsOpen set to True if the Options dialog should stay open when
#       leaving this function
# param alreadyOnOptionsDialog set to True if you already have opened the Options Dialog
#       (if False this functions will open it via the MenuBar -> Tools -> Options...)
# param additionalFunction pass a function or name of a defined function to execute
#       for each configured item on the list of Kits
#       this function must take at least 2 parameters - the first is the item (QModelIndex)
#       of the current Kit (if you need to click on it) and the second the Kit name itself
# param argsForAdditionalFunc you can specify as much parameters as you want to pass
#       to additionalFunction from the outside
# the function returns a list of Kit names if used without an additional function
# WATCH OUT! if you're using the additionalFunction parameter - this function will
# return the list mentioned above as well as the returned value(s) from
# additionalFunction. You MUST call this function like
# result, additionalResult = _iterateQtVersions(...)
# where additionalResult is the result of all executions of additionalFunction which
# means it is a list of results.
def iterateKits(keepOptionsOpen=False, alreadyOnOptionsDialog=False,
                additionalFunction=None, *argsForAdditionalFunc):
    result = []
    additionalResult = []
    if not alreadyOnOptionsDialog:
        invokeMenuItem("Tools", "Options...")
    waitForObjectItem(":Options_QListView", "Build & Run")
    clickItem(":Options_QListView", "Build & Run", 14, 15, 0, Qt.LeftButton)
581
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Kits")
582
    treeView = waitForObject(":Kits_Or_Compilers_QTreeView")
583
584
585
586
587
588
589
590
    model = treeView.model()
    test.compare(model.rowCount(), 2, "Verifying expected target section count")
    autoDetected = model.index(0, 0)
    test.compare(autoDetected.data().toString(), "Auto-detected",
                 "Verifying label for target section")
    manual = model.index(1, 0)
    test.compare(manual.data().toString(), "Manual", "Verifying label for target section")
    for section in [autoDetected, manual]:
591
592
        for currentItem in dumpItems(model, section):
            kitName = currentItem
593
594
595
596
            if (kitName.endswith(" (default)")):
                kitName = kitName.rsplit(" (default)", 1)[0]
            result.append(kitName)
            item = ".".join([str(section.data().toString()),
597
                             currentItem.replace(".", "\\.")])
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
            if additionalFunction:
                try:
                    if isinstance(additionalFunction, (str, unicode)):
                        currResult = globals()[additionalFunction](item, kitName, *argsForAdditionalFunc)
                    else:
                        currResult = additionalFunction(item, kitName, *argsForAdditionalFunc)
                except:
                    import sys
                    t,v,tb = sys.exc_info()
                    currResult = None
                    test.fatal("Function to additionally execute on Options Dialog could not be "
                               "found or an exception occured while executing it.", "%s(%s)" %
                               (str(t), str(v)))
                additionalResult.append(currResult)
    if not keepOptionsOpen:
613
614
615
616
617
        clickButton(waitForObject(":Options.Cancel_QPushButton"))
    if additionalFunction:
        return result, additionalResult
    else:
        return result
618
619
620
621
622
623

# set "Always Start Full Help" in "Tools" -> "Options..." -> "Help" -> "General"
def setAlwaysStartFullHelp():
    invokeMenuItem("Tools", "Options...")
    waitForObjectItem(":Options_QListView", "Help")
    clickItem(":Options_QListView", "Help", 5, 5, 0, Qt.LeftButton)
624
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "General")
625
626
627
628
629
630
631
632
633
634
    selectFromCombo(":Startup.contextHelpComboBox_QComboBox", "Always Start Full Help")
    clickButton(waitForObject(":Options.OK_QPushButton"))

def removePackagingDirectory(projectPath):
    qtcPackaging = os.path.join(projectPath, "qtc_packaging")
    if os.path.exists(qtcPackaging):
        test.log("Removing old packaging directory '%s'" % qtcPackaging)
        deleteDirIfExists(qtcPackaging)
    else:
        test.log("Couldn't remove packaging directory '%s' - did not exist." % qtcPackaging)
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650

# returns the indices from a QAbstractItemModel
def dumpIndices(model, parent=None, column=0):
    if parent:
        return [model.index(row, column, parent) for row in range(model.rowCount(parent))]
    else:
        return [model.index(row, column) for row in range(model.rowCount())]

DisplayRole = 0
# returns the data from a QAbstractItemModel as strings
def dumpItems(model, parent=None, role=DisplayRole, column=0):
    return [str(index.data(role)) for index in dumpIndices(model, parent, column)]

# returns the children of a QTreeWidgetItem
def dumpChildren(item):
    return [item.child(index) for index in range(item.childCount())]
651
652
653
654
655
656
657
658
659
660
661
662
663
664

def writeTestResults(folder):
    if squishinfo.version < 0x040200FF:
        print "Skipping writing test results (Squish < 4.2)"
        return
    if not os.path.exists(folder):
        print "Skipping writing test results (folder '%s' does not exist)." % folder
        return
    resultFile = open("%s.srf" % os.path.join(folder, os.path.basename(squishinfo.testCase)), "w")
    resultFile.write("suite:%s\n" % os.path.basename(os.path.dirname(squishinfo.testCase)))
    categories = ["passes", "fails", "fatals", "errors", "tests", "warnings", "xfails", "xpasses"]
    for cat in categories:
        resultFile.write("%s:%d\n" % (cat, test.resultCount(cat)))
    resultFile.close()
665
666
667
668
669
670
671
672
673

# wait and verify if object exists/not exists
def checkIfObjectExists(name, shouldExist = True, timeout = 3000, verboseOnFail = False):
    result = waitFor("object.exists(name) == shouldExist", timeout)
    if verboseOnFail and not result:
        test.log("checkIfObjectExists() failed for '%s'" % name)
    return result

# wait for progress bar(s) to appear and disappear
674
def progressBarWait(timeout=60000, warn=True):
675
    if not checkIfObjectExists(":Qt Creator_Core::Internal::ProgressBar", True, 6000):
676
677
678
        if warn:
            test.warning("progressBarWait() timed out when waiting for ProgressBar.",
                         "This may lead to unforeseen behavior. Consider increasing the timeout.")
679
    checkIfObjectExists(":Qt Creator_Core::Internal::ProgressBar", False, timeout)
680
681
682
683
684
685

def readFile(filename):
    f = open(filename, "r")
    content = f.read()
    f.close()
    return content
686
687
688

def simpleFileName(navigatorFileName):
    return ".".join(navigatorFileName.split(".")[-2:]).replace("\\","")
689
690
691
692
693
694
695
696
697
698

def clickOnTab(tabBarStr, tabText, timeout=5000):
    if platform.system() == 'Darwin':
        if not waitFor("object.exists(tabBarStr)", timeout):
            raise LookupError("Could not find QTabBar: %s" % objectMap.realName(tabBarStr))
        tabBar = findObject(tabBarStr)
        if not tabBar.visible:
            test.log("Using workaround for Mac.")
            setWindowState(tabBar, WindowState.Normal)
    clickTab(waitForObject(tabBarStr, timeout), tabText)
699
700
701
702
703
704
705
706
707

# constructs a string holding the properties for a QModelIndex
# param property a string holding additional properties including their values
#       ATTENTION! use single quotes for values (e.g. "text='Text'", "text='Text' occurrence='2'")
# param container the container (str) to be used for this QModelIndex
def getQModelIndexStr(property, container):
    if (container.startswith(":")):
        container = "'%s'" % container
    return ("{column='0' container=%s %s type='QModelIndex'}" % (container, property))