project.py 28.5 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 __builtin__
31
32
import re

33
34
35
processStarted = False
processExited = False

36
def __handleProcessStarted__(*args):
37
38
39
    global processStarted
    processStarted = True

40
def __handleProcessExited__(*args):
41
42
43
    global processExited
    processExited = True

Christian Stenger's avatar
Christian Stenger committed
44
def openQmakeProject(projectPath, targets=Targets.desktopTargetClasses(), fromWelcome=False):
45
    cleanUpUserFiles(projectPath)
46
47
48
    if fromWelcome:
        mouseClick(waitForObject(":OpenProject_QStyleItem"), 5, 5, 0, Qt.LeftButton)
        if not platform.system() == "Darwin":
49
            waitFor("waitForObject(':fileNameEdit_QLineEdit', 1000).focus == True", 3000)
50
51
    else:
        invokeMenuItem("File", "Open File or Project...")
52
    selectFromFileDialog(projectPath)
53
54
    try:
        # handle update generated files dialog
55
56
57
        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)
58
59
60
        clickButton(waitForObject("{text='Yes' type='QPushButton' unnamed='1' visible='1'}"))
    except:
        pass
61
    checkedTargets = __chooseTargets__(targets)
62
    configureButton = waitForObject("{text='Configure Project' type='QPushButton' unnamed='1' visible='1'"
63
                                    "window=':Qt Creator_Core::Internal::MainWindow'}")
64
    clickButton(configureButton)
65
    return checkedTargets
66

67
def openCmakeProject(projectPath, buildDir):
68
    invokeMenuItem("File", "Open File or Project...")
69
    selectFromFileDialog(projectPath)
70
71
    replaceEditorContent("{type='Utils::BaseValidatingLineEdit' unnamed='1' visible='1'"
                         "window=':CMake Wizard_CMakeProjectManager::Internal::CMakeOpenProjectWizard'}", buildDir)
72
    clickButton(waitForObject(":CMake Wizard.Next_QPushButton"))
73
    generatorCombo = waitForObject(":Generator:_QComboBox")
74
75
76
    mkspec = __getMkspecFromQmake__("qmake")
    test.log("Using mkspec '%s'" % mkspec)

77
    generatorText = "Unix Generator (Desktop 474 GCC)"
78
    if "win32-" in mkspec:
79
        generatorName = {"win32-g++" : "MinGW Generator (Desktop 474 GCC)",
80
                         "win32-msvc2010" : "NMake Generator (Desktop 480 MSVC2010)"}
81
        if mkspec in generatorName:
82
83
84
85
86
87
            generatorText = generatorName[mkspec]
    index = generatorCombo.findText(generatorText)
    if index == -1:
        test.warning("No matching CMake generator for mkspec '%s' found." % mkspec)
    else:
        generatorCombo.setCurrentIndex(index)
88

89
    clickButton(waitForObject(":CMake Wizard.Run CMake_QPushButton"))
Christian Stenger's avatar
Christian Stenger committed
90
91
92
93
94
95
96
97
98
99
    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
100

101
102
103
104
# 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__()
105
def __createProjectOrFileSelectType__(category, template, fromWelcome = False, isProject=True):
106
107
108
109
    if fromWelcome:
        mouseClick(waitForObject(":CreateProject_QStyleItem"), 5, 5, 0, Qt.LeftButton)
    else:
        invokeMenuItem("File", "New File or Project...")
110
    categoriesView = waitForObject("{type='QTreeView' name='templateCategoryView'}")
111
112
113
114
    if isProject:
        clickItem(categoriesView, "Projects." + category, 5, 5, 0, Qt.LeftButton)
    else:
        clickItem(categoriesView, "Files and Classes." + category, 5, 5, 0, Qt.LeftButton)
115
    templatesView = waitForObject("{name='templatesView' type='QListView'}")
116
    clickItem(templatesView, template, 5, 5, 0, Qt.LeftButton)
117
    text = waitForObject("{type='QTextBrowser' name='templateDescription' visible='1'}").plainText
118
    clickButton(waitForObject("{text='Choose...' type='QPushButton' unnamed='1' visible='1'}"))
119
    return __getSupportedPlatforms__(str(text))[0]
120

121
def __createProjectSetNameAndPath__(path, projectName = None, checks = True):
122
    directoryEdit = waitForObject("{type='Utils::BaseValidatingLineEdit' unnamed='1' visible='1'}")
123
124
    replaceEditorContent(directoryEdit, path)
    projectNameEdit = waitForObject("{name='nameLineEdit' visible='1' "
125
                                    "type='Utils::ProjectNameValidatingLineEdit'}")
126
127
128
129
130
131
132
133
134
    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
135
    ensureChecked("{type='QCheckBox' name='projectsDirectoryCheckBox' visible='1'}", False)
136
    clickButton(waitForObject(":Next_QPushButton"))
137
    return str(projectName)
138

139
140
# Selects the Qt versions for a project
# param checks turns tests in the function on if set to True
141
# param available a list holding the available targets
142
def __selectQtVersionDesktop__(checks, available=None):
Christian Stenger's avatar
Christian Stenger committed
143
    checkedTargets = __chooseTargets__(Targets.desktopTargetClasses(), available)
144
    if checks:
145
146
147
148
        cbObject = ("{type='QCheckBox' text='%s' unnamed='1' visible='1' "
                    "container={type='Utils::DetailsWidget' visible='1' unnamed='1'}}")
        verifyChecked(cbObject % "Debug")
        verifyChecked(cbObject % "Release")
149
    clickButton(waitForObject(":Next_QPushButton"))
150
    return checkedTargets
151

152
def __createProjectHandleLastPage__(expectedFiles = None):
153
    if expectedFiles != None:
154
155
        summary = str(waitForObject("{name='filesLabel' text?='<qt>Files to be added in<pre>*</pre>'"
                                    "type='QLabel' visible='1'}").text)
156
157
158
159
160
161
        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>")
162
    clickButton(waitForObject("{type='QPushButton' text~='(Finish|Done)' visible='1'}"))
163

164
165
166
167
168
169
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")

170
171
172
173
# 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
174
def createProject_Qt_GUI(path, projectName, checks = True):
175
    template = "Qt Gui Application"
176
    available = __createProjectOrFileSelectType__("  Applications", template)
177
    __createProjectSetNameAndPath__(path, projectName, checks)
178
    checkedTargets = __selectQtVersionDesktop__(checks, available)
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

    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)

195
    clickButton(waitForObject(":Next_QPushButton"))
196

197
    expectedFiles = None
198
    if checks:
199
200
        if platform.system() in ('Windows', 'Microsoft'):
            path = os.path.abspath(path)
Robert Loehning's avatar
Robert Loehning committed
201
        path = os.path.join(path, projectName)
202
        expectedFiles = [path]
203
        expectedFiles.extend(__sortFilenamesOSDependent__(["main.cpp", cpp_file, h_file, ui_file, pro_file]))
204
    __createProjectHandleLastPage__(expectedFiles)
205

206
    progressBarWait(20000)
207
    __verifyFileCreation__(path, expectedFiles)
208
    return checkedTargets
209

210
211
212
213
# 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
214
def createProject_Qt_Console(path, projectName, checks = True):
215
    available = __createProjectOrFileSelectType__("  Applications", "Qt Console Application")
216
    __createProjectSetNameAndPath__(path, projectName, checks)
217
    checkedTargets = __selectQtVersionDesktop__(checks, available)
218

219
220
221
222
223
224
225
    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"
226
227
        expectedFiles = [path]
        expectedFiles.extend(__sortFilenamesOSDependent__([cpp_file, pro_file]))
228
    __createProjectHandleLastPage__(expectedFiles)
229

230
    progressBarWait(10000)
231
    __verifyFileCreation__(path, expectedFiles)
232
    return checkedTargets
233

234
def createNewQtQuickApplication(workingDir, projectName = None, templateFile = None,
Christian Stenger's avatar
Christian Stenger committed
235
                                targets=Targets.desktopTargetClasses(), qtQuickVersion=1,
236
                                fromWelcome=False):
237
    if templateFile:
238
239
        available = __createProjectOrFileSelectType__("  Applications", "Qt Quick %d Application (from Existing QML File)"
                                                      % qtQuickVersion, fromWelcome)
240
    else:
Robert Loehning's avatar
Robert Loehning committed
241
        available = __createProjectOrFileSelectType__("  Applications", "Qt Quick %d Application (Built-in Types)"
242
                                                % qtQuickVersion, fromWelcome)
243
244
    projectName = __createProjectSetNameAndPath__(workingDir, projectName)
    if templateFile:
245
        baseLineEd = waitForObject("{type='Utils::BaseValidatingLineEdit' unnamed='1' visible='1'}")
246
        type(baseLineEd, templateFile)
247
        nextButton = waitForObject(":Next_QPushButton")
248
        clickButton(nextButton)
249
    checkedTargets = __chooseTargets__(targets, available)
250
    snooze(1)
251
    nextButton = waitForObject(":Next_QPushButton")
252
    clickButton(nextButton)
253
    __createProjectHandleLastPage__()
254

255
    progressBarWait(10000)
256
    return checkedTargets, projectName
257
258

def createNewQtQuickUI(workingDir):
259
    __createProjectOrFileSelectType__("  Applications", "Qt Quick 1 UI")
260
261
    if workingDir == None:
        workingDir = tempDir()
262
    projectName = __createProjectSetNameAndPath__(workingDir)
263
    __createProjectHandleLastPage__()
264
    return projectName
265
266

def createNewQmlExtension(workingDir):
267
    available = __createProjectOrFileSelectType__("  Libraries", "Qt Quick 1 Extension Plugin")
268
269
    if workingDir == None:
        workingDir = tempDir()
270
    __createProjectSetNameAndPath__(workingDir)
Christian Stenger's avatar
Christian Stenger committed
271
    checkedTargets = __chooseTargets__(Targets.DESKTOP_474_GCC, available)
272
    nextButton = waitForObject(":Next_QPushButton")
273
    clickButton(nextButton)
274
    nameLineEd = waitForObject("{buddy={type='QLabel' text='Object class-name:' unnamed='1' visible='1'} "
275
                               "type='QLineEdit' unnamed='1' visible='1'}")
276
277
    replaceEditorContent(nameLineEd, "TestItem")
    uriLineEd = waitForObject("{buddy={type='QLabel' text='URI:' unnamed='1' visible='1'} "
278
                              "type='QLineEdit' unnamed='1' visible='1'}")
Robert Loehning's avatar
Robert Loehning committed
279
    replaceEditorContent(uriLineEd, "org.qt-project.test.qmlcomponents")
280
    clickButton(nextButton)
281
    __createProjectHandleLastPage__()
282
    return checkedTargets
283

Christian Stenger's avatar
Christian Stenger committed
284
# parameter target can be an OR'd value of Targets
285
286
# parameter availableTargets should be the result of __createProjectSelectType__()
#           or use None as a fallback
Christian Stenger's avatar
Christian Stenger committed
287
def __chooseTargets__(targets=Targets.DESKTOP_474_GCC, availableTargets=None,
288
                      isMaddeDisabled=True):
289
290
291
292
    if availableTargets != None:
        available = availableTargets
    else:
        # following targets depend on the build environment - added for further/later tests
293
294
        available = [Targets.DESKTOP_474_GCC, Targets.DESKTOP_480_GCC, Targets.DESKTOP_501_DEFAULT,
                     Targets.MAEMO5, Targets.EMBEDDED_LINUX, Targets.SIMULATOR, Targets.HARMATTAN]
295
        if platform.system() in ('Windows', 'Microsoft'):
Christian Stenger's avatar
Christian Stenger committed
296
            available.remove(Targets.EMBEDDED_LINUX)
297
            available.append(Targets.DESKTOP_480_MSVC2010)
298
299
    if isMaddeDisabled:
        for target in filter(lambda x: x in available,
Christian Stenger's avatar
Christian Stenger committed
300
                             (Targets.MAEMO5, Targets.HARMATTAN)):
301
            available.remove(target)
302
    checkedTargets = []
303
304
305
    for current in available:
        mustCheck = targets & current == current
        try:
Christian Stenger's avatar
Christian Stenger committed
306
            ensureChecked("{type='QCheckBox' text='%s' visible='1'}" % Targets.getStringForTarget(current),
307
                          mustCheck, 3000)
308
309
            if (mustCheck):
                checkedTargets.append(current)
310
311
        except LookupError:
            if mustCheck:
Christian Stenger's avatar
Christian Stenger committed
312
                test.fail("Failed to check target '%s'." % Targets.getStringForTarget(current))
313
            else:
314
                # Simulator has been added without knowing whether configured or not - so skip warning here?
315
                if current != Targets.SIMULATOR:
Christian Stenger's avatar
Christian Stenger committed
316
                    test.warning("Target '%s' is not set up correctly." % Targets.getStringForTarget(current))
317
    return checkedTargets
318
319
320
321
322
323
324
325
326
327
328
329
330
331

# 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
332
    overrideInstallLazySignalHandler()
333
334
    installLazySignalHandler("{type='QProcess'}", "started()", "__handleProcessStarted__")
    installLazySignalHandler("{type='QProcess'}", "finished(int,QProcess::ExitStatus)", "__handleProcessExited__")
335
    runButton = waitForObject(":*Qt Creator.Run_Core::Internal::FancyToolButton")
336
337
338
339
340
341
342
343
344
345
346
347
348
    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
349
    if sType == SubprocessType.QT_QUICK_UI and os.getenv("SYSTEST_QMLVIEWER_NO_HOOK_INTO", "0") == "1":
350
        withHookInto = False
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
    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):
374
    ensureChecked(":Qt Creator_AppOutput_Core::Internal::OutputPaneToggleButton")
375
376
377
378
    try:
        waitForObject(":Qt Creator.Stop_QToolButton", 5000)
    except:
        pass
379
380
381
382
383
384
385
    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":
386
            waitFor("stopButton.enabled==False")
387
388
389
390
391
392
393
            snooze(2)
            nativeType("<Escape>")
    else:
        test.fatal("Subprocess does not seem to have been started.")

def __closeSubprocessByHookingInto__(executable, port, function, sType, userDefType):
    global processExited
394
    ensureChecked(":Qt Creator_AppOutput_Core::Internal::OutputPaneToggleButton")
395
    output = waitForObject("{type='Core::OutputWindow' visible='1' windowTitle='Application Output Window'}")
396
397
398
399
400
401
402
403
    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:
        resetApplicationContextToCreator()
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
        if "Loading Qt Wrapper failed" in str(output.plainText):
            test.warning("Loading of Qt Wrapper failed - probably different Qt versions.",
                         "Resetting hook-into settings to continue.")
            # assuming we're still on the build settings of the current project (TODO)
            switchViewTo(ViewConstants.PROJECTS)
            if sType == SubprocessType.QT_QUICK_UI:
                selectConfig = "QML Viewer"
            else:
                selectConfig = executable
            selectFromCombo(waitForObject("{buddy={text='Run configuration:' type='QLabel' "
                                          "unnamed='1' visible='1'} type='QComboBox' unnamed='1' "
                                          "visible='1'}"), selectConfig)
            switchViewTo(ViewConstants.EDIT)
            global processStarted
            processStarted = False
419
            runButton = waitForObject(":*Qt Creator.Run_Core::Internal::FancyToolButton")
420
421
422
423
424
425
426
427
428
            clickButton(runButton)
            if not waitFor("processStarted == True", 10000):
                test.fatal("Something seems to be really wrong.", "Application output:"
                           % str(output.plainText))
                return False
            else:
                test.log("Application seems to be started without hooking-into.")
        else:
            test.warning("Could not attach to '%s' - using fallback of pushing STOP inside Creator." % executable)
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
        __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)
448
    waitFor("processExited==True and 'exited with code' in str(output.plainText)", 10000)
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
    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)
465
466
467
468
469

# 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
470
# if you set getAsStrings to True this function returns a list of strings instead
Christian Stenger's avatar
Christian Stenger committed
471
# of the constants defined in Targets
472
473
474
475
476
477
478
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
479
480
481
482
    if 'Supported Platforms' in text:
        supports = text[text.find('Supported Platforms'):].split(":")[1].strip().split(" ")
        result = []
        if 'Desktop' in supports:
483
484
485
486
487
488
489
            if version == None or version < "5.0":
                result.append(Targets.DESKTOP_474_GCC)
                result.append(Targets.DESKTOP_480_GCC)
                if platform.system() in ("Linux", "Darwin"):
                    result.append(Targets.EMBEDDED_LINUX)
                elif platform.system() in ('Windows', 'Microsoft'):
                    result.append(Targets.DESKTOP_480_MSVC2010)
Christian Stenger's avatar
Christian Stenger committed
490
            result.append(Targets.DESKTOP_501_DEFAULT)
491
        if 'MeeGo/Harmattan' in supports:
Christian Stenger's avatar
Christian Stenger committed
492
            result.append(Targets.HARMATTAN)
493
        if 'Maemo/Fremantle' in supports:
Christian Stenger's avatar
Christian Stenger committed
494
            result.append(Targets.MAEMO5)
495
        if not re.search("custom Qt Creator plugin", text) and (version == None or version < "5.0"):
Christian Stenger's avatar
Christian Stenger committed
496
            result.append(Targets.SIMULATOR)
497
    elif 'Platform independent' in text:
498
        # MAEMO5 and HARMATTAN could be wrong here - depends on having Madde plugin enabled or not
499
500
        result = [Targets.DESKTOP_474_GCC, Targets.DESKTOP_480_GCC, Targets.DESKTOP_501_DEFAULT,
                  Targets.MAEMO5, Targets.SIMULATOR, Targets.HARMATTAN]
Robert Loehning's avatar
Robert Loehning committed
501
        if platform.system() in ('Windows', 'Microsoft'):
502
            result.append(Targets.DESKTOP_480_MSVC2010)
503
504
505
    else:
        test.warning("Returning None (__getSupportedPlatforms__())",
                     "Parsed text: '%s'" % text)
506
507
        return None, None
    if getAsStrings:
Christian Stenger's avatar
Christian Stenger committed
508
        result = Targets.getTargetsAsStrings(result)
509
    return result, version
510
511
512
513

# copy example project (sourceExample is path to project) to temporary directory inside repository
def prepareTemplate(sourceExample):
    templateDir = os.path.abspath(tempDir() + "/template")
514
515
516
517
518
    try:
        shutil.copytree(sourceExample, templateDir)
    except:
        test.fatal("Error while copying '%s' to '%s'" % (sourceExample, templateDir))
        return None
519
    return templateDir
520
521
522
523
524
525
526

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

528
529
def __iterateChildren__(model, parent, nestingLevel=0):
    children = []
530
    for currentIndex in dumpIndices(model, parent):
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
        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")
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586

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))
587
588
589
590
591
592
593
594
595
596

def qt5SDKPath():
    if platform.system() in ('Microsoft', 'Windows'):
        return os.path.abspath("C:/Qt/Qt5.0.1/5.0.1/msvc2010")
    elif platform.system() == 'Linux':
        if __is64BitOS__():
            return os.path.expanduser("~/Qt5.0.1/5.0.1/gcc_64")
        return os.path.expanduser("~/Qt5.0.1/5.0.1/gcc")
    else:
        return os.path.expanduser("~/Qt5.0.1/5.0.1/clang_64")