aboutsummaryrefslogtreecommitdiffstats
path: root/squishtests/suite_neptune3/shared/scripts/bdd_hooks.py
blob: a4fde0ec847b6dedfdf124d86a371cde49d2acb4 (plain)
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# -*- coding: utf-8 -*-

############################################################################
##
## Copyright (C) 2019 Luxoft Sweden AB
## Copyright (C) 2018 Pelagicore AG
## Contact: https://www.qt.io/licensing/
##
## This file is part of the Neptune 3 IVI UI.
##
## $QT_BEGIN_LICENSE:GPL-QTAS$
## Commercial License Usage
## Licensees holding valid commercial Qt Automotive Suite 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 The Qt Company.  For
## licensing terms and conditions see https://www.qt.io/terms-conditions.
## For further information use the contact form at https://www.qt.io/contact-us.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 3 or (at your option) any later version
## approved by the KDE Free Qt Foundation. The licenses are as published by
## the Free Software Foundation and appearing in the file LICENSE.GPL3
## included in the packaging of this file. Please review the following
## information to ensure the GNU General Public License requirements will
## be met: https://www.gnu.org/licenses/gpl-3.0.html.
##
## $QT_END_LICENSE$
##
## SPDX-License-Identifier: GPL-3.0
##
#############################################################################


import math
import os          # needed for app identification path
import __builtin__ as builtins  # python types (not squish)

import common.settings as settings
import common.app as app

# squish dependent
import names
import squish
import test

# waiting time to let all windows to arrange at start-up
STARTUP_ARRANGE_TIME_SEC = 2
END_DEARRANGE_TIME_SEC = 3


@OnFeatureEnd
def hook(context):
    for ctx in applicationContextList():
        ctx.detach()
    squish.snooze(END_DEARRANGE_TIME_SEC)


# clean up a little more
def start_neptune_ui_app_w_focus(window):
    """ Starting hook for all tests to be started. It can be started in 2 modes
    which selects which window of neptune should be focused (for a visible
    experience and double check the tests' effect)

    'console'   : console view focused
    'dashboard' : dashboard view focused
    """

    # check forced single process:
    # it can be used to start in single process though it would normally
    # start in multi-process, this is just passing through of an option
    # which is also defined in starting neptune3-ui executable
    force_single_process = (os.environ.get('SINGLE_PROCESS') == '1')

    # !!! Remember to use ignoredauts.txt feature
    # otherwise this will cause a lot of trouble,
    # with dbus and remotesettings-server !!!
    # Read the documentation:
    # https://doc.qt.io/Neptune3UI/neptune3ui-testing-squish.html#exclude-disruptive-sub-processes
    command_line_options = ("-r"
                          + " --start-session-dbus"
                          + " -c am-config-neptune.yaml"
                          + " -c squish-appman-hook.yaml"
                          + (" --force-single-process" if
                             force_single_process else ""))

    # assemble the line
    command_line = settings.G_AUT_MAIN + " " + command_line_options

    test.log("command_line: " + command_line)

    try:
        # try to start application
        app_context = squish.startApplication(command_line)
    except Exception as e:
        test.fail("direct command line call didn't work:", str(e))
        return False

    test.log("Started applicationContext: '" + app_context.name + "' ("
             + str(app_context.pid) + ", #" + str(app_context.port)
             + ") is running!")

    # this snooze is really needed, VERY IMPORTANT
    squish.snooze(STARTUP_ARRANGE_TIME_SEC)

    # try to register all already connected AUTs
    # especially from appman
    nr_apps = app.update_all_contexts()

    # setting multi process according to how many apps
    # were found
    settings.G_MULTI_PROCESS = (nr_apps > 1)
    test.log("Using " + ("MULTI" if settings.G_MULTI_PROCESS
                        else "SINGLE")
                      + " PROCESS!!")

    # if it is multi process, change search container for
    # all according apps
    if settings.G_MULTI_PROCESS:
        # change for all known apps the search container
        for change_app in names.apps_change_collection:
            change_app(names.multi_process_container)

    # to be able to focus window we need the neptune main app
    app.switch_to_main_app()

    try:
        worked, window_obj = get_focus_window(window)

        if not worked:
            return False
    except Exception as e:
            test.fail("Window not found!! (" + str(e) + ")")
            return False

    # only for console so far
    test.log("Window size is   : " + str(window_obj.width)
             + "x" + str(window_obj.height))
    test.log("Window pos  is   : " + str(window_obj.x)
             + "," + str(window_obj.y))

    # look for center console
    try:
        console_obj = squish.waitForObject(
                        names.neptune_3_UI_Center_Console_centerConsole_CenterConsole,
                        500)
    except Exception:
        test.fail("Could not find console window!!!")
    else:
        # look also into
        # https://doc.froglogic.com/squish/latest/rgs-squish.html#rgss-screen-object
        test.log("----------------------")
        settings.SCREEN_WIDTH = console_obj.width
        settings.SCREEN_HEIGHT = console_obj.height

        settings.SCREEN_LANDSCAPE = console_obj.store.centerConsole.isLandscape

        test.log("Landscape" if settings.SCREEN_LANDSCAPE else "No landscape")

        # I misuse it to distinguish between target and test development
        if settings.SCREEN_LANDSCAPE:
            settings.G_WAIT_SYSTEM_READY_SEC = 3

        test.log("Console size     : " + str(settings.SCREEN_WIDTH)
                  + "x" + str(settings.SCREEN_HEIGHT))
        test.log("Console offset is: " + str(console_obj.x)
                  + "," + str(console_obj.y))

        # from https://kb.froglogic.com/display/KB/Problem+-+Bringing+window+to+foreground+%28Qt%29
        window_obj.show()
        getattr(window_obj, "raise")()


def get_focus_window(window):
    """Return the object to the window according to dashboard/cluster"""
    found = True
    if window == "dashboard":
        obj_name = names.neptune_UI_Instrument_Cluster_QQuickWindowQmlImpl
    elif window == "console":
        obj_name = names.neptune_UI_Center_Console
    else:
        test.fail("The given window '" + window + "' is not known!!")
        obj = None
        found = False
        return found, obj
    try:
        obj = squish.waitForObject(obj_name, 1000)
    except Exception as e:
        test.fail("Could not find window '" + window + "'!!" + str(e))
        obj = None
        found = False
    return found, obj


# todo: move these to another file
def get_middle_of_object(obj):
    try:
        posx = obj.x
        posy = obj.y
    except Exception as e:
        test.fail("Fail due to: " + str(e))
        return False, QPoint(0, 0)
    else:
        return True, QPoint(posx, posy)


def get_info(obj):
    try:
        posx = obj.x
        posy = obj.y
        width = obj.width
        height = obj.height
    except Exception as e:
        test.fail("Fail due to: " + str(e))
    else:
        test.log("(" + str(posx) + "," + str(posy)
                 + ") size ["
                 + str(width) + "," + str(height) + "]")


def get_midth_of_item(itemObjectOrName):
    """Returns (success, QPoint) of the center point of the given object"""
    item = waitForObject(itemObjectOrName)
    if className(item) != "QQuickItem":
        try:
            item = object.convertTo(item, "QQuickItem")
        except Exception as e:
            test.log("Positioning object couldn't be converted to QQuickItem: "
                      + str(e))
            return False, QPoint(0, 0)
    return True, QPoint(item.x + math.floor(item.width / 2), item.y
                               + math.floor(item.height / 2))


def find_object_name_recursively(obj, obj_name, max_depth):
    """Find a given objectName string in the subtree of the given object, up
     to max depth levels"""
    if max_depth > 0:
        deep_children = object.children(obj)
        for dc in deep_children:
            if hasattr(dc, "objectName") and dc.objectName == obj_name:
                return dc
            children_search = find_object_name_recursively(dc,
                                                           obj_name,
                                                           max_depth - 1)
            if children_search:
                return children_search
    else:
        return None


def find_same_prefix_list(obj, list_prefix, max_depth):
    """Find a (child) listlist of object with same prefix,
    which are in same level (siblings)
    to max depth levels of the starting object.
    The staring child 0 has to exist, and also we assume
    that digits for low number don't have 001 or 01."""
    return_obj_list = None
    if max_depth > 0:
        zero_element_name = list_prefix + "0"
        zero_element = find_object_name_recursively(obj, zero_element_name,
                                                    max_depth)
        if zero_element is not None:
            parent = object.parent(zero_element)
            if parent is not None:
                # now check all children for same prefix and add
                chdl = object.children(parent)
                for chd in chdl:
                    if not hasattr(chd, "objectName"):
                        continue
                    full_obj_name = str(chd.objectName)
                    suffix = full_obj_name.replace(list_prefix, "")
                    # test that removing prefix doesn't
                    # do anything
                    if suffix == full_obj_name:
                        continue
                    _try_number = 0
                    try:
                        _try_number = builtins.int(suffix)
                    except ValueError:
                        continue
                    # here it should be ok
                    # one could check, if it is a counting up
                    # number (to before) or if it is +1 always
                    # ... this will be a first cheap version,
                    # taking anything that fits
                    if return_obj_list is None:
                        # first entry
                        return_obj_list = [chd]
                    else:
                        return_obj_list.append(chd)
    return return_obj_list


def get_position_item(itemObjectOrName):
    """Gets the position of the given object in the coordinates of the
     root object"""
    def recursive_go_deep(obj):
        parent = object.parent(obj)
        if parent:
            worked, rel_pos = recursive_go_deep(parent)
            if worked:
                posx = obj.x + rel_pos.x
                posy = obj.y + rel_pos.y
                return True, QPoint(posx, posy)
            else:
                return False, QPoint(0, 0)
        else:
            return True, QPoint(obj.x, obj.y)

    item = waitForObject(itemObjectOrName)
    # from https://kb.froglogic.com/display/KB/Getting+screen+coordinates+of+QGraphicsItem%2C+QGraphicsObject
    if className(item) != "QQuickItem":
        try:
            item = object.convertTo(item, "QQuickItem")
        except Exception as e:
            test.log("Positioning object couldn't be converted to QQuickItem: "
                      + str(e))
            return False, QPoint(0, 0)
    worked, pos = recursive_go_deep(item)
    return worked, pos