project.py 26 KB
Newer Older
1
import __builtin__
2 3
import re

4 5 6 7 8 9 10 11 12 13 14
processStarted = False
processExited = False

def __handleProcessStarted__(object):
    global processStarted
    processStarted = True

def __handleProcessExited__(object, exitCode):
    global processExited
    processExited = True

15
def openQmakeProject(projectPath, targets = QtQuickConstants.Targets.DESKTOP_474_GCC, fromWelcome = False):
16
    cleanUpUserFiles(projectPath)
17 18 19 20 21 22
    if fromWelcome:
        mouseClick(waitForObject(":OpenProject_QStyleItem"), 5, 5, 0, Qt.LeftButton)
        if not platform.system() == "Darwin":
            waitFor("waitForObject(':fileNameEdit_QLineEdit').focus == True")
    else:
        invokeMenuItem("File", "Open File or Project...")
23
    selectFromFileDialog(projectPath)
24 25
    try:
        # handle update generated files dialog
26 27 28
        waitForObject("{type='QLabel' name='qt_msgbox_label' visible='1' "
                      "text?='The following files are either outdated or have been modified*' "
                      "window={type='QMessageBox' unnamed='1' visible='1'}}", 3000)
29 30 31
        clickButton(waitForObject("{text='Yes' type='QPushButton' unnamed='1' visible='1'}"))
    except:
        pass
32
    __chooseTargets__(targets)
33
    configureButton = waitForObject("{text='Configure Project' type='QPushButton' unnamed='1' visible='1'"
34
                                    "window=':Qt Creator_Core::Internal::MainWindow'}")
35
    clickButton(configureButton)
36

37
def openCmakeProject(projectPath, buildDir):
38
    invokeMenuItem("File", "Open File or Project...")
39
    selectFromFileDialog(projectPath)
40 41
    replaceEditorContent("{type='Utils::BaseValidatingLineEdit' unnamed='1' visible='1'"
                         "window=':CMake Wizard_CMakeProjectManager::Internal::CMakeOpenProjectWizard'}", buildDir)
42
    clickButton(waitForObject(":CMake Wizard.Next_QPushButton"))
43
    generatorCombo = waitForObject(":Generator:_QComboBox")
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
    mkspec = __getMkspecFromQmake__("qmake")
    test.log("Using mkspec '%s'" % mkspec)

    if "win32-" in mkspec:
        generatorName = {"win32-g++" : "MinGW Generator (MinGW from SDK)",
                         "win32-msvc2008" : "NMake Generator (Microsoft Visual C++ Compiler 9.0 (x86))",
                         "win32-msvc2010" : "NMake Generator (Microsoft Visual C++ Compiler 10.0 (x86))"}
        index = -1
        if mkspec in generatorName:
            index = generatorCombo.findText(generatorName[mkspec])
        if index == -1:
            test.warning("No matching CMake generator for mkspec '%s' found." % mkspec)
        else:
            generatorCombo.setCurrentIndex(index)

59
    clickButton(waitForObject(":CMake Wizard.Run CMake_QPushButton"))
Christian Stenger's avatar
Christian Stenger committed
60 61 62 63 64 65 66 67 68 69
    try:
        clickButton(waitForObject(":CMake Wizard.Finish_QPushButton", 60000))
    except LookupError:
        cmakeOutput = waitForObject("{type='QPlainTextEdit' unnamed='1' visible='1' "
                                    "window=':CMake Wizard_CMakeProjectManager::Internal::CMakeOpenProjectWizard'}")
        test.warning("Error while executing cmake - see details for cmake output.",
                     str(cmakeOutput.plainText))
        clickButton(waitForObject(":CMake Wizard.Cancel_QPushButton"))
        return False
    return True
70

71 72 73 74
# this function returns a list of available targets - this is not 100% error proof
# because the Simulator target is added for some cases even when Simulator has not
# been set up inside Qt versions/Toolchains
# this list can be used in __chooseTargets__()
75
def __createProjectOrFileSelectType__(category, template, fromWelcome = False, isProject=True):
76 77 78 79
    if fromWelcome:
        mouseClick(waitForObject(":CreateProject_QStyleItem"), 5, 5, 0, Qt.LeftButton)
    else:
        invokeMenuItem("File", "New File or Project...")
80
    categoriesView = waitForObject("{type='QTreeView' name='templateCategoryView'}")
81 82 83 84
    if isProject:
        clickItem(categoriesView, "Projects." + category, 5, 5, 0, Qt.LeftButton)
    else:
        clickItem(categoriesView, "Files and Classes." + category, 5, 5, 0, Qt.LeftButton)
85
    templatesView = waitForObject("{name='templatesView' type='QListView'}")
86
    clickItem(templatesView, template, 5, 5, 0, Qt.LeftButton)
87
    text = waitForObject("{type='QTextBrowser' name='templateDescription' visible='1'}").plainText
88
    clickButton(waitForObject("{text='Choose...' type='QPushButton' unnamed='1' visible='1'}"))
89
    return __getSupportedPlatforms__(str(text))[0]
90

91
def __createProjectSetNameAndPath__(path, projectName = None, checks = True):
92
    directoryEdit = waitForObject("{type='Utils::BaseValidatingLineEdit' unnamed='1' visible='1'}")
93 94
    replaceEditorContent(directoryEdit, path)
    projectNameEdit = waitForObject("{name='nameLineEdit' visible='1' "
95
                                    "type='Utils::ProjectNameValidatingLineEdit'}")
96 97 98 99 100 101 102 103 104
    if projectName == None:
        projectName = projectNameEdit.text
    else:
        replaceEditorContent(projectNameEdit, projectName)
    if checks:
        stateLabel = findObject("{type='QLabel' name='stateLabel'}")
        labelCheck = stateLabel.text=="" and stateLabel.styleSheet == ""
        test.verify(labelCheck, "Project name and base directory without warning or error")
    # make sure this is not set as default location
105
    ensureChecked("{type='QCheckBox' name='projectsDirectoryCheckBox' visible='1'}", False)
106
    clickButton(waitForObject(":Next_QPushButton"))
107
    return str(projectName)
108

109 110
# Selects the Qt versions for a project
# param checks turns tests in the function on if set to True
111
# param available a list holding the available targets
112
def __selectQtVersionDesktop__(checks, available=None):
113
    __chooseTargets__(QtQuickConstants.Targets.DESKTOP_474_GCC, available)
114
    if checks:
115 116 117 118
        cbObject = ("{type='QCheckBox' text='%s' unnamed='1' visible='1' "
                    "container={type='Utils::DetailsWidget' visible='1' unnamed='1'}}")
        verifyChecked(cbObject % "Debug")
        verifyChecked(cbObject % "Release")
119 120
    clickButton(waitForObject(":Next_QPushButton"))

121
def __createProjectHandleLastPage__(expectedFiles = None):
122
    if expectedFiles != None:
123 124
        summary = str(waitForObject("{name='filesLabel' text?='<qt>Files to be added in<pre>*</pre>'"
                                    "type='QLabel' visible='1'}").text)
125 126 127 128 129 130
        lastIndex = 0
        for filename in expectedFiles:
            index = summary.find(filename)
            test.verify(index > lastIndex, "'" + filename + "' found at index " + str(index))
            lastIndex = index
    selectFromCombo(":addToVersionControlComboBox_QComboBox", "<None>")
131
    clickButton(waitForObject("{type='QPushButton' text~='(Finish|Done)' visible='1'}"))
132

133 134 135 136 137 138
def __verifyFileCreation__(path, expectedFiles):
    for filename in expectedFiles:
        if filename != path:
            filename = os.path.join(path, filename)
        test.verify(os.path.exists(filename), "Checking if '" + filename + "' was created")

139 140 141 142
# Creates a Qt GUI project
# param path specifies where to create the project
# param projectName is the name for the new project
# param checks turns tests in the function on if set to True
143
def createProject_Qt_GUI(path, projectName, checks = True):
144
    template = "Qt Gui Application"
145
    available = __createProjectOrFileSelectType__("  Applications", template)
146
    __createProjectSetNameAndPath__(path, projectName, checks)
147
    __selectQtVersionDesktop__(checks, available)
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

    if checks:
        exp_filename = "mainwindow"
        h_file = exp_filename + ".h"
        cpp_file = exp_filename + ".cpp"
        ui_file = exp_filename + ".ui"
        pro_file = projectName + ".pro"

        waitFor("object.exists(':headerFileLineEdit_Utils::FileNameValidatingLineEdit')", 20000)
        waitFor("object.exists(':sourceFileLineEdit_Utils::FileNameValidatingLineEdit')", 20000)
        waitFor("object.exists(':formFileLineEdit_Utils::FileNameValidatingLineEdit')", 20000)

        test.compare(findObject(":headerFileLineEdit_Utils::FileNameValidatingLineEdit").text, h_file)
        test.compare(findObject(":sourceFileLineEdit_Utils::FileNameValidatingLineEdit").text, cpp_file)
        test.compare(findObject(":formFileLineEdit_Utils::FileNameValidatingLineEdit").text, ui_file)

164
    clickButton(waitForObject(":Next_QPushButton"))
165

166
    expectedFiles = None
167
    if checks:
168 169
        if platform.system() in ('Windows', 'Microsoft'):
            path = os.path.abspath(path)
Robert Loehning's avatar
Robert Loehning committed
170
        path = os.path.join(path, projectName)
171
        expectedFiles = [path]
172
        expectedFiles.extend(__sortFilenamesOSDependent__(["main.cpp", cpp_file, h_file, ui_file, pro_file]))
173
    __createProjectHandleLastPage__(expectedFiles)
174

175 176 177
    waitForSignal("{type='CppTools::Internal::CppModelManager' unnamed='1'}", "sourceFilesRefreshed(QStringList)", 20000)
    __verifyFileCreation__(path, expectedFiles)

178 179 180 181
# Creates a Qt Console project
# param path specifies where to create the project
# param projectName is the name for the new project
# param checks turns tests in the function on if set to True
182
def createProject_Qt_Console(path, projectName, checks = True):
183
    available = __createProjectOrFileSelectType__("  Applications", "Qt Console Application")
184
    __createProjectSetNameAndPath__(path, projectName, checks)
185
    __selectQtVersionDesktop__(checks, available)
186

187 188 189 190 191 192 193
    expectedFiles = None
    if checks:
        if platform.system() in ('Windows', 'Microsoft'):
            path = os.path.abspath(path)
        path = os.path.join(path, projectName)
        cpp_file = "main.cpp"
        pro_file = projectName + ".pro"
194 195
        expectedFiles = [path]
        expectedFiles.extend(__sortFilenamesOSDependent__([cpp_file, pro_file]))
196
    __createProjectHandleLastPage__(expectedFiles)
197

198 199
    waitForSignal("{type='CppTools::Internal::CppModelManager' unnamed='1'}", "sourceFilesRefreshed(QStringList)", 10000)
    __verifyFileCreation__(path, expectedFiles)
200

201
def createNewQtQuickApplication(workingDir, projectName = None, templateFile = None,
202
                                targets = QtQuickConstants.Targets.DESKTOP_474_GCC, qtQuickVersion=1,
203
                                fromWelcome=False):
204
    if templateFile:
205 206 207 208
        if qtQuickVersion == 2:
            test.fatal('There is no wizard "Qt Quick 2 Application (from Existing QML File)"',
                       'This is a script error. Using Qt Quick 1 instead.')
        available = __createProjectOrFileSelectType__("  Applications", "Qt Quick 1 Application (from Existing QML File)", fromWelcome)
209
    else:
210
        available = __createProjectOrFileSelectType__("  Applications", "Qt Quick %d Application (Built-in Elements)"
211
                                                % qtQuickVersion, fromWelcome)
212 213
    projectName = __createProjectSetNameAndPath__(workingDir, projectName)
    if templateFile:
214
        baseLineEd = waitForObject("{type='Utils::BaseValidatingLineEdit' unnamed='1' visible='1'}")
215
        type(baseLineEd, templateFile)
216
        nextButton = waitForObject(":Next_QPushButton")
217 218
        clickButton(nextButton)
    __chooseTargets__(targets, available)
219
    snooze(1)
220
    nextButton = waitForObject(":Next_QPushButton")
221
    clickButton(nextButton)
222
    __createProjectHandleLastPage__()
223
    return projectName
224 225

def createNewQtQuickUI(workingDir):
226
    __createProjectOrFileSelectType__("  Applications", "Qt Quick UI")
227 228
    if workingDir == None:
        workingDir = tempDir()
229
    projectName = __createProjectSetNameAndPath__(workingDir)
230
    __createProjectHandleLastPage__()
231
    return projectName
232 233

def createNewQmlExtension(workingDir):
234
    available = __createProjectOrFileSelectType__("  Libraries", "Qt Quick 1 Extension Plugin")
235 236
    if workingDir == None:
        workingDir = tempDir()
237
    __createProjectSetNameAndPath__(workingDir)
238
    __chooseTargets__(QtQuickConstants.Targets.DESKTOP_474_GCC, available)
239
    nextButton = waitForObject(":Next_QPushButton")
240 241
    clickButton(nextButton)
    nameLineEd = waitForObject("{buddy={type='QLabel' text='Object Class-name:' unnamed='1' visible='1'} "
242
                               "type='QLineEdit' unnamed='1' visible='1'}")
243 244
    replaceEditorContent(nameLineEd, "TestItem")
    uriLineEd = waitForObject("{buddy={type='QLabel' text='URI:' unnamed='1' visible='1'} "
245
                              "type='QLineEdit' unnamed='1' visible='1'}")
Robert Loehning's avatar
Robert Loehning committed
246
    replaceEditorContent(uriLineEd, "org.qt-project.test.qmlcomponents")
247
    clickButton(nextButton)
248
    __createProjectHandleLastPage__()
249 250 251 252

# parameter components can only be one of the Constants defined in QtQuickConstants.Components
def __chooseComponents__(components=QtQuickConstants.Components.BUILTIN):
    rbComponentToChoose = waitForObject("{type='QRadioButton' text='%s' visible='1'}"
253
                              % QtQuickConstants.getStringForComponents(components))
254 255 256 257 258 259 260 261
    if rbComponentToChoose.checked:
        test.passes("Selected QRadioButton is '%s'" % QtQuickConstants.getStringForComponents(components))
    else:
        clickButton(rbComponentToChoose)
        test.verify(rbComponentToChoose.checked, "Selected QRadioButton is '%s'"
                % QtQuickConstants.getStringForComponents(components))

# parameter target can be an OR'd value of QtQuickConstants.Targets
262 263
# parameter availableTargets should be the result of __createProjectSelectType__()
#           or use None as a fallback
264
def __chooseTargets__(targets=QtQuickConstants.Targets.DESKTOP_474_GCC, availableTargets=None):
265 266 267 268
    if availableTargets != None:
        available = availableTargets
    else:
        # following targets depend on the build environment - added for further/later tests
269
        available = [QtQuickConstants.Targets.DESKTOP_474_GCC,
Christian Stenger's avatar
Christian Stenger committed
270
                     QtQuickConstants.Targets.MAEMO5, QtQuickConstants.Targets.EMBEDDED_LINUX,
271 272
                     QtQuickConstants.Targets.SIMULATOR, QtQuickConstants.Targets.HARMATTAN]
        if platform.system() in ('Windows', 'Microsoft'):
273
            available.remove(QtQuickConstants.Targets.EMBEDDED_LINUX)
Robert Loehning's avatar
Robert Loehning committed
274
            available.append(QtQuickConstants.Targets.DESKTOP_474_MSVC2008)
275 276 277 278
    for current in available:
        mustCheck = targets & current == current
        try:
            ensureChecked("{type='QCheckBox' text='%s' visible='1'}" % QtQuickConstants.getStringForTarget(current),
279
                          mustCheck, 3000)
280 281
        except LookupError:
            if mustCheck:
282 283
                test.fail("Failed to check target '%s'." % QtQuickConstants.getStringForTarget(current))
            else:
284 285 286
                # Simulator has been added without knowing whether configured or not - so skip warning here?
                if current != QtQuickConstants.Targets.SIMULATOR:
                    test.warning("Target '%s' is not set up correctly." % QtQuickConstants.getStringForTarget(current))
287 288 289 290 291 292 293 294 295 296 297 298 299 300

# run and close an application
# withHookInto - if set to True the function tries to attach to the sub-process instead of simply pressing Stop inside Creator
# executable - must be defined when using hook-into
# port - must be defined when using hook-into
# function - can be a string holding a function name or a reference to the function itself - this function will be called on
# the sub-process when hooking-into has been successful - if its missing simply closing the Qt Quick app will be done
# sType the SubprocessType - is nearly mandatory - except when using the function parameter
# userDefinedType - if you set sType to SubprocessType.USER_DEFINED you must(!) specify the WindowType for hooking into
# by yourself (or use the function parameter)
# ATTENTION! Make sure this function won't fail and the sub-process will end when the function returns
def runAndCloseApp(withHookInto=False, executable=None, port=None, function=None, sType=None, userDefinedType=None):
    global processStarted, processExited
    processStarted = processExited = False
301
    overrideInstallLazySignalHandler()
302 303
    installLazySignalHandler("{type='ProjectExplorer::ApplicationLaucher'}", "processStarted()", "__handleProcessStarted__")
    installLazySignalHandler("{type='ProjectExplorer::ApplicationLaucher'}", "processExited(int)", "__handleProcessExited__")
304
    runButton = waitForObject("{type='Core::Internal::FancyToolButton' text='Run' visible='1'}")
305 306 307 308 309 310 311 312 313 314 315 316 317
    clickButton(runButton)
    if sType != SubprocessType.QT_QUICK_UI:
        waitForSignal("{type='ProjectExplorer::BuildManager' unnamed='1'}", "buildQueueFinished(bool)", 300000)
        buildSucceeded = checkLastBuild()
        if not buildSucceeded:
            test.fatal("Build inside run wasn't successful - leaving test")
            invokeMenuItem("File", "Exit")
            return False
    waitFor("processStarted==True", 10000)
    if not processStarted:
        test.fatal("Couldn't start application - leaving test")
        invokeMenuItem("File", "Exit")
        return False
318
    if sType == SubprocessType.QT_QUICK_UI and os.getenv("SYSTEST_QMLVIEWER_NO_HOOK_INTO", "0") == "1":
319
        withHookInto = False
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    if withHookInto and not validType(sType, userDefinedType):
        if function != None:
            test.warning("You did not provide a valid value for the SubprocessType value - sType, but you have "
                         "provided a function to execute on the subprocess. Please ensure that your function "
                         "closes the subprocess before exiting, or this test will not complete.")
        else:
            test.warning("You did not provide a valid value for the SubprocessType value - sType, nor a "
                         "function to execute on the subprocess. Falling back to pushing the STOP button "
                         "inside creator to terminate execution of the subprocess.")
            withHookInto = False
    if withHookInto and not executable in ("", None):
        __closeSubprocessByHookingInto__(executable, port, function, sType, userDefinedType)
    else:
        __closeSubprocessByPushingStop__(sType)
    return True

def validType(sType, userDef):
    if sType == None:
        return False
    ty = SubprocessType.getWindowType(sType)
    return ty != None and not (ty == "user-defined" and (userDef == None or userDef.strip() == ""))

def __closeSubprocessByPushingStop__(sType):
343
    ensureChecked(":Qt Creator_AppOutput_Core::Internal::OutputPaneToggleButton")
344 345 346 347
    try:
        waitForObject(":Qt Creator.Stop_QToolButton", 5000)
    except:
        pass
348 349 350 351 352 353 354
    playButton = verifyEnabled(":Qt Creator.ReRun_QToolButton", False)
    stopButton = verifyEnabled(":Qt Creator.Stop_QToolButton")
    if stopButton.enabled:
        clickButton(stopButton)
        test.verify(playButton.enabled)
        test.compare(stopButton.enabled, False)
        if sType == SubprocessType.QT_QUICK_UI and platform.system() == "Darwin":
355
            waitFor("stopButton.enabled==False")
356 357 358 359 360 361 362
            snooze(2)
            nativeType("<Escape>")
    else:
        test.fatal("Subprocess does not seem to have been started.")

def __closeSubprocessByHookingInto__(executable, port, function, sType, userDefType):
    global processExited
363
    ensureChecked(":Qt Creator_AppOutput_Core::Internal::OutputPaneToggleButton")
364
    output = waitForObject("{type='Core::OutputWindow' visible='1' windowTitle='Application Output Window'}")
365 366 367 368 369 370 371
    if port == None:
        test.warning("I need a port number or attaching might fail.")
    else:
        waitFor("'Listening on port %d for incoming connectionsdone' in str(output.plainText)" % port, 5000)
    try:
        attachToApplication(executable)
    except:
372
        test.warning("Could not attach to '%s' - using fallback of pushing STOP inside Creator." % executable)
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
        resetApplicationContextToCreator()
        __closeSubprocessByPushingStop__(sType)
        return False
    if function == None:
        if sType==SubprocessType.USER_DEFINED:
            sendEvent("QCloseEvent", "{type='%s' unnamed='1' visible='1'}" % userDefType)
        else:
            sendEvent("QCloseEvent", "{type='%s' unnamed='1' visible='1'}" % SubprocessType.getWindowType(sType))
        resetApplicationContextToCreator()
    else:
        try:
            if isinstance(function, (str, unicode)):
                globals()[function]()
            else:
                function()
        except:
            test.fatal("Function to execute on sub-process could not be found.",
                       "Using fallback of pushing STOP inside Creator.")
            resetApplicationContextToCreator()
            __closeSubprocessByPushingStop__(sType)
    waitFor("processExited==True", 10000)
    if not processExited:
        test.warning("Sub-process seems not to have closed properly.")
        try:
            resetApplicationContextToCreator()
            __closeSubprocessByPushingStop__(sType)
        except:
            pass
    return True

# this helper tries to reset the current application context back
# to creator - this strange work-around is needed _sometimes_ on MacOS
def resetApplicationContextToCreator():
    appCtxt = applicationContext("qtcreator")
    if appCtxt.name == "":
        appCtxt = applicationContext("Qt Creator")
    setApplicationContext(appCtxt)
410 411 412 413 414

# helper that examines the text (coming from the create project wizard)
# to figure out which available targets we have
# Simulator must be handled in a special way, because this depends on the
# configured Qt versions and Toolchains and cannot be looked up the same way
415 416 417 418 419 420 421 422 423
# if you set getAsStrings to True this function returns a list of strings instead
# of the constants defined in QtQuickConstants.Targets
def __getSupportedPlatforms__(text, getAsStrings=False):
    reqPattern = re.compile("requires qt (?P<version>\d+\.\d+(\.\d+)?)", re.IGNORECASE)
    res = reqPattern.search(text)
    if res:
        version = res.group("version")
    else:
        version = None
424 425 426 427 428
    if 'Supported Platforms' in text:
        supports = text[text.find('Supported Platforms'):].split(":")[1].strip().split(" ")
        result = []
        addSimulator = False
        if 'Desktop' in supports:
429
            result.append(QtQuickConstants.Targets.DESKTOP_474_GCC)
430 431
            if platform.system() in ("Linux", "Darwin"):
                result.append(QtQuickConstants.Targets.EMBEDDED_LINUX)
Robert Loehning's avatar
Robert Loehning committed
432 433
            elif platform.system() in ('Windows', 'Microsoft'):
                result.append(QtQuickConstants.Targets.DESKTOP_474_MSVC2008)
434 435
        if 'MeeGo/Harmattan' in supports:
            result.append(QtQuickConstants.Targets.HARMATTAN)
436 437
            addSimulator = True
        if 'Maemo/Fremantle' in supports:
438 439 440 441 442
            result.append(QtQuickConstants.Targets.MAEMO5)
            addSimulator = True
        if len(result) == 0 or addSimulator:
            result.append(QtQuickConstants.Targets.SIMULATOR)
    elif 'Platform independent' in text:
443
        result = [QtQuickConstants.Targets.DESKTOP_474_GCC, QtQuickConstants.Targets.MAEMO5,
444
                  QtQuickConstants.Targets.SIMULATOR, QtQuickConstants.Targets.HARMATTAN]
Robert Loehning's avatar
Robert Loehning committed
445 446
        if platform.system() in ('Windows', 'Microsoft'):
            result.append(QtQuickConstants.Targets.DESKTOP_474_MSVC2008)
447 448 449
    else:
        test.warning("Returning None (__getSupportedPlatforms__())",
                     "Parsed text: '%s'" % text)
450 451 452 453
        return None, None
    if getAsStrings:
        result = QtQuickConstants.getTargetsAsStrings(result)
    return result, version
454 455 456 457

# copy example project (sourceExample is path to project) to temporary directory inside repository
def prepareTemplate(sourceExample):
    templateDir = os.path.abspath(tempDir() + "/template")
458 459 460 461 462
    try:
        shutil.copytree(sourceExample, templateDir)
    except:
        test.fatal("Error while copying '%s' to '%s'" % (sourceExample, templateDir))
        return None
463
    return templateDir
464 465 466 467 468 469 470

def __sortFilenamesOSDependent__(filenames):
    if platform.system() in ('Windows', 'Microsoft'):
        filenames.sort(key=str.lower)
    else:
        filenames.sort()
    return filenames
471

472 473
def __iterateChildren__(model, parent, nestingLevel=0):
    children = []
474
    for currentIndex in dumpIndices(model, parent):
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
        children.append([str(currentIndex.text), nestingLevel])
        if model.hasChildren(currentIndex):
            children.extend(__iterateChildren__(model, currentIndex, nestingLevel + 1))
    return children

# This will write the data to a file which can then be used for comparing
def __writeProjectTreeFile__(projectTree, filename):
    f = open(filename, "w+")
    f.write('"text"\t"nestinglevel"\n')
    for elem in projectTree:
        f.write('"%s"\t"%s"\n' % (elem[0], elem[1]))
    f.close()

def __getTestData__(record):
    return [testData.field(record, "text"),
            __builtin__.int(testData.field(record, "nestinglevel"))]

def compareProjectTree(rootObject, dataset):
    root = waitForObject(rootObject)
    tree = __iterateChildren__(root.model(), root)

    # __writeProjectTreeFile__(tree, dataset)

    for i, current in enumerate(map(__getTestData__, testData.dataset(dataset))):
        try:
            # Just removing everything up to the found item
            # Writing a pass would result in truly massive logs
            tree = tree[tree.index(current) + 1:]
        except ValueError:
            test.fail('Could not find "%s" with nesting level %s' % tuple(current),
                      'Line %s in dataset' % str(i + 1))
            return
    test.passes("No errors found in project tree")
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

def addCPlusPlusFileToCurrentProject(name, template, forceOverwrite=False):
    if name == None:
        test.fatal("File must have a name - got None.")
        return
    __createProjectOrFileSelectType__("  C++", template, isProject=False)
    window = "{type='Utils::FileWizardDialog' unnamed='1' visible='1'}"
    basePath = str(waitForObject("{type='Utils::BaseValidatingLineEdit' unnamed='1' visible='1' "
                                 "window=%s}" % window).text)
    lineEdit = waitForObject("{name='nameLineEdit' type='Utils::FileNameValidatingLineEdit' "
                             "visible='1' window=%s}" % window)
    replaceEditorContent(lineEdit, name)
    clickButton(waitForObject(":Next_QPushButton"))
    __createProjectHandleLastPage__()
    if (os.path.exists(os.path.join(basePath, name))):
        overwriteDialog = "{type='Core::Internal::PromptOverwriteDialog' unnamed='1' visible='1'}"
        waitForObject(overwriteDialog)
        if forceOverwrite:
            buttonToClick = 'OK'
        else:
            buttonToClick = 'Cancel'
        clickButton("{text='%s' type='QPushButton' unnamed='1' visible='1' window=%s}"
                    % (buttonToClick, overwriteDialog))