File: ui_wrapper.py

package info (click to toggle)
python-traitsui 8.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,232 kB
  • sloc: python: 58,982; makefile: 113
file content (377 lines) | stat: -rw-r--r-- 11,991 bytes parent folder | download
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
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
372
373
374
375
376
377
# (C) Copyright 2004-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!

""" Define the top-level object which is responsible for dispatching testing
functionality for a given GUI object. The functionality is exposed via
``UITester``, which is a TraitsUI specific tester.
"""

from contextlib import contextmanager
import textwrap

from traitsui.testing._exception_handling import (
    reraise_exceptions as _reraise_exceptions,
)
from traitsui.testing._gui import (
    process_cascade_events as _process_cascade_events,
)
from traitsui.testing.tester import locator
from traitsui.testing.tester.exceptions import (
    InteractionNotSupported,
    LocationNotSupported,
)


class UIWrapper:
    """
    An ``UIWrapper`` has the following responsibilities:

    (1) Wraps a UI target.
    (2) Search for a nested UI target within the wrapped UI target.
    (3) Perform user interaction on the UI target, e.g. mouse click.

    A UI target is an object which can be searched for nested UI targets,
    either as intermediate things (like editors or a table widget), or as a
    leaf widget which can be operated upon (e.g. a mouse click).

    For example, a ``UIWrapper`` may wrap an instance of traitsui.ui.UI in
    which more UI targets can be located. A ``UIWrapper`` may also wrap a
    leaf widget on which user interactions can be performed.

    For locating a nested UI target, the ``locate`` method is provided.
    For simulating user interactions such as a mouse click or visual
    inspection, the ``perform`` and ``inspect`` methods are provided.

    Parameters
    ----------
    target : any
        An object on which further UI target can be searched for, or can be
        a leaf target that can be operated on.
    registries : list of AbstractTargetRegistry
        Registries of interaction for different target, in the order
        of decreasing priority.
    delay : int, optional
        Time delay (in ms) in which actions by the wrapper are performed. Note
        it is propagated through to created child wrappers. The delay allows
        visual confirmation test code is working as desired. Defaults to 0.
    auto_process_events : bool, optional
        Whether to process (cascade) GUI events automatically. Default is True.
        For tests that launch a modal dialog and rely on a recurring timer to
        poll if the dialog is closed, it may be necessary to set this flag to
        false in order to avoid deadlocks. Note that this is propagated
        through to created child wrappers.

    Attributes
    ----------
    delay : int
        Time delay (in ms) in which actions by the wrapper are performed. Note
        it is propagated through to created child wrappers. The delay allows
        visual confirmation test code is working as desired.
    _target : any
        The UI target currently wrapped for interactions or locating nested
        components. This is a protected attribute intended to be used for
        extending the testing API. Usage of this attribute may expose the
        software's internal structure to the tests, developers should use this
        attribute with discretion based on context.
    """

    def __init__(
        self, target, *, registries, delay=0, auto_process_events=True
    ):
        self._target = target
        self._registries = registries
        self._auto_process_events = auto_process_events
        self.delay = delay

    def help(self):
        """Print help messages.
        (This function is intended for interactive use.)
        """
        # mapping from interaction types to their documentation
        interaction_to_doc = dict()

        # mapping from location types to their documentation
        location_to_doc = dict()

        # Order registries by their priority (low to high)
        for registry in self._registries[::-1]:
            for type_ in registry._get_interactions(self._target):
                interaction_to_doc[type_] = registry._get_interaction_doc(
                    target=self._target,
                    interaction_class=type_,
                )

            for type_ in registry._get_locations(self._target):
                location_to_doc[type_] = registry._get_location_doc(
                    target=self._target,
                    locator_class=type_,
                )

        print("Interactions")
        print("------------")
        for interaction_type in sorted(interaction_to_doc, key=repr):
            print(repr(interaction_type))
            print(
                textwrap.indent(
                    interaction_to_doc[interaction_type], prefix="    "
                )
            )
            print()

        if not interaction_to_doc:
            print("No interactions are supported.")
            print()

        print("Locations")
        print("---------")
        for locator_type in sorted(location_to_doc, key=repr):
            print(repr(locator_type))
            print(
                textwrap.indent(location_to_doc[locator_type], prefix="    ")
            )
            print()

        if not location_to_doc:
            print("No locations are supported.")
            print()

    def locate(self, location):
        """Attempt to resolve the given location and return a new
        UIWrapper.

        Parameters
        ----------
        location : any
            An instance of a location type supported by the current target.
            e.g. ``traitsui.testing.api.Index(1)``

        Returns
        -------
        wrapper : UIWrapper
            A new UIWrapper for the given location.

        Raises
        ------
        LocationNotSupported
            If the given location is not supported.

        See Also
        --------
        UIWrapper.help
        """
        return UIWrapper(
            target=self._get_next_target(location),
            registries=self._registries,
            delay=self.delay,
            auto_process_events=self._auto_process_events,
        )

    def find_by_name(self, name):
        """Find a target inside the current target using a name.

        This is equivalent to calling ``locate(TargetByName(name=name))``.

        Parameters
        ----------
        name : str
            A single name for retreiving a target on a UI.

        Returns
        -------
        wrapper : UIWrapper

        Raises
        ------
        LocationNotSupported
            If the current target does not support locating another target
            by a name.

        See Also
        --------
        traitsui.testing.tester.locator.TargetByName
        """
        return self.locate(locator.TargetByName(name=name))

    def find_by_id(self, id):
        """Find a target inside the current target using an id.

        This is equivalent to calling ``locate(TargetById(id=id))``.

        Parameters
        ----------
        id : str
            Id for finding an item in the UI.

        Returns
        -------
        wrapper : UIWrapper

        Raises
        ------
        LocationNotSupported
            If the current target does not support locating another target
            by a unique identifier.

        See Also
        --------
        traitsui.testing.tester.locator.TargetById
        """
        return self.locate(locator.TargetById(id=id))

    def perform(self, interaction):
        """Perform a user interaction that causes side effects.

        Parameters
        ----------
        interaction : object
            An instance of an interaction type supported by the current target.
            e.g. ``traitsui.testing.api.MouseClick()``

        Raises
        ------
        InteractionNotSupported
            If the interaction given is not supported for the current UI
            target.

        See Also
        --------
        UIWrapper.help
        """
        self._perform_or_inspect(interaction)

    def inspect(self, interaction):
        """Return a value or values for inspection.

        Parameters
        ----------
        interaction : object
            An instance of an interaction type supported by the current target.
            e.g. ``traitsui.testing.api.DisplayedText()``

        Returns
        -------
        values : any
            Any values returned for the given inspection. The type should be
            documented by the interaction type object.

        Raises
        ------
        InteractionNotSupported
            If the interaction given is not supported for the current UI
            target.

        See Also
        --------
        UIWrapper.help
        """
        return self._perform_or_inspect(interaction)

    # Private methods #########################################################

    def _perform_or_inspect(self, interaction):
        """Perform a user interaction or a user inspection.

        Parameters
        ----------
        interaction : instance of interaction type
            An object defining the interaction.

        Returns
        -------
        value : any

        Raises
        ------
        InteractionNotSupported
            If the given interaction does not have a corresponding
            implementation for the wrapped UI target.
        """
        supported = []
        for registry in self._registries:
            try:
                handler = registry._get_handler(
                    target=self._target,
                    interaction=interaction,
                )
            except InteractionNotSupported as e:
                supported.extend(e.supported)
                continue
            else:
                context = (
                    _event_processed
                    if self._auto_process_events
                    else _nullcontext
                )
                with context():
                    return handler(self, interaction)

        raise InteractionNotSupported(
            target_class=self._target.__class__,
            interaction_class=interaction.__class__,
            supported=supported,
        )

    def _get_next_target(self, location):
        """Return the next UI target from the given location.

        Parameters
        ----------
        location : instance of locator type
            A location for resolving the next target.

        Returns
        -------
        new_target : any

        Raises
        ------
        LocationNotSupport
            If no solver are provided for resolving the given location in the
            wrapped UI target.
        """
        supported = set()
        for registry in self._registries:
            try:
                handler = registry._get_solver(
                    target=self._target,
                    location=location,
                )
            except LocationNotSupported as e:
                supported |= set(e.supported)
            else:
                if self._auto_process_events:
                    with _reraise_exceptions():
                        _process_cascade_events()
                return handler(self, location)

        raise LocationNotSupported(
            target_class=self._target.__class__,
            locator_class=location.__class__,
            supported=list(supported),
        )


@contextmanager
def _event_processed():
    """Context manager to ensure GUI events are processed upon entering
    and exiting the context.
    """
    with _reraise_exceptions():
        _process_cascade_events()
        try:
            yield
        finally:
            _process_cascade_events()


@contextmanager
def _nullcontext():
    """Equivalent to contextlib.nullcontext() in Python >= 3.7"""
    yield