File: test_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 (530 lines) | stat: -rw-r--r-- 15,458 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
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# (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!

import io
import textwrap
import unittest
from unittest import mock

from pyface.api import GUI

from traits.api import HasTraits, Int
from traits.testing.api import UnittestTools
from traitsui.tests._tools import (
    process_cascade_events,
    requires_toolkit,
    ToolkitName,
)
from traitsui.testing.tester._abstract_target_registry import (
    AbstractTargetRegistry,
)
from traitsui.testing.tester.exceptions import (
    InteractionNotSupported,
    LocationNotSupported,
)
from traitsui.testing.tester.target_registry import (
    TargetRegistry,
)
from traitsui.testing.tester.ui_wrapper import (
    UIWrapper,
)


def example_ui_wrapper(**kwargs):
    """Return an instance of UIWrapper for testing purposes.

    Parameters
    ----------
    **kwargs
        Values to use instead of the default values.

    Returns
    -------
    wrapper: UIWrapper
    """
    values = dict(
        target=None,
        registries=[],
    )
    values.update(kwargs)
    return UIWrapper(**values)


class StubRegistry(AbstractTargetRegistry):
    """A stub implementation of the AbstractTargetRegistry for testing"""

    def __init__(
        self,
        handler=None,
        solver=None,
        supported_interaction_classes=(),
        supported_locator_classes=(),
        interaction_doc="",
        location_doc="",
    ):
        self.handler = handler
        self.solver = solver
        self.supported_interaction_classes = supported_interaction_classes
        self.supported_locator_classes = supported_locator_classes
        self.interaction_doc = interaction_doc
        self.location_doc = location_doc

    def _get_handler(self, target, interaction):
        if interaction.__class__ not in self.supported_interaction_classes:
            raise InteractionNotSupported(
                target_class=target.__class__,
                interaction_class=interaction.__class__,
                supported=list(self.supported_interaction_classes),
            )
        return self.handler

    def _get_interactions(self, target):
        return set(self.supported_interaction_classes)

    def _get_interaction_doc(self, target, interaction_class):
        return self.interaction_doc

    def _get_solver(self, target, location):
        if location.__class__ not in self.supported_locator_classes:
            raise LocationNotSupported(
                target_class=target.__class__,
                locator_class=location.__class__,
                supported=list(self.supported_locator_classes),
            )
        return self.solver

    def _get_locations(self, target):
        return set(self.supported_locator_classes)

    def _get_location_doc(self, target, locator_class):
        return self.location_doc


# Use of perform/inspect requires the GUI event loop
@requires_toolkit([ToolkitName.qt, ToolkitName.wx])
class TestUIWrapperInteractionRegistries(unittest.TestCase):
    """Test the logic regarding the order of (interaction) registries."""

    def test_registry_priority(self):
        # If two registries have a handler for the same target and interaction
        # types, the first register is used.
        registry1 = StubRegistry(
            handler=lambda w, l: 1,
            supported_interaction_classes=[str],
        )
        registry2 = StubRegistry(
            handler=lambda w, l: 2,
            supported_interaction_classes=[str],
        )

        wrapper = example_ui_wrapper(
            registries=[registry2, registry1],
        )
        value = wrapper.inspect("some string")

        self.assertEqual(value, 2)

        # reverse order
        wrapper = example_ui_wrapper(registries=[registry1, registry2])
        value = wrapper.inspect("some other string")

        self.assertEqual(value, 1)

    def test_registry_selection(self):
        # If the first registry says it can't handle the interaction, the next
        # registry is tried.

        registry1 = StubRegistry()
        registry2_handler = mock.Mock()
        registry2 = StubRegistry(
            handler=registry2_handler,
            supported_interaction_classes=[int],
        )

        wrapper = example_ui_wrapper(
            registries=[registry1, registry2],
        )
        wrapper.perform(123)

        self.assertEqual(registry2_handler.call_count, 1)

    def test_registry_all_declined(self):
        # If none of the registries can support an interaction, the
        # exception raised provide information on what actions are
        # supported.

        wrapper = example_ui_wrapper(
            registries=[
                StubRegistry(supported_interaction_classes=[int]),
                StubRegistry(supported_interaction_classes=[float]),
            ],
        )
        with self.assertRaises(InteractionNotSupported) as exception_context:
            wrapper.perform(None)

        self.assertCountEqual(
            exception_context.exception.supported,
            [int, float],
        )


# Use of locate requires the GUI event loop
@requires_toolkit([ToolkitName.qt, ToolkitName.wx])
class TestUIWrapperLocationRegistry(unittest.TestCase):
    """Test the use of registries with locate."""

    def test_location_registry_priority(self):
        registry1 = StubRegistry(
            solver=lambda w, l: 1,
            supported_locator_classes=[str],
        )
        registry2 = StubRegistry(
            solver=lambda w, l: 2,
            supported_locator_classes=[str],
        )

        wrapper = example_ui_wrapper(
            registries=[registry2, registry1],
        )
        new_wrapper = wrapper.locate("some string")

        self.assertEqual(new_wrapper._target, 2)

        # swap the order
        wrapper = example_ui_wrapper(
            registries=[registry1, registry2],
        )
        new_wrapper = wrapper.locate("some other string")

        self.assertEqual(new_wrapper._target, 1)

    def test_location_registry_selection(self):
        # If the first registry says it can't handle the interaction, the next
        # registry is tried.

        def solver2(wrapper, location):
            return 2

        registry1 = StubRegistry()
        registry2 = StubRegistry(
            solver=solver2,
            supported_locator_classes=[str],
        )

        wrapper = example_ui_wrapper(
            registries=[registry1, registry2],
        )
        new_wrapper = wrapper.locate("some string")

        self.assertEqual(new_wrapper._target, 2)
        self.assertEqual(
            new_wrapper._registries,
            wrapper._registries,
        )

    def test_registry_all_declined(self):
        # If none of the registries can support a location, the
        # exception raised provide information on what actions are
        # supported.

        wrapper = example_ui_wrapper(
            registries=[
                StubRegistry(supported_locator_classes=[int]),
                StubRegistry(supported_locator_classes=[float]),
            ],
        )
        with self.assertRaises(LocationNotSupported) as exception_context:
            wrapper.locate(None)

        self.assertCountEqual(
            exception_context.exception.supported,
            [int, float],
        )


class TestUIWrapperHelp(unittest.TestCase):
    """Test calling UIWrapper.help"""

    def test_help_message(self):
        class Action:
            """Say hello.
            Say bye.
            """

            pass

        class Locator:
            """Return anything you like.
            Good day!
            """

            pass

        registry1 = TargetRegistry()
        registry1.register_interaction(
            target_class=str,
            interaction_class=Action,
            handler=mock.Mock(),
        )
        registry2 = TargetRegistry()
        registry2.register_location(
            target_class=str,
            locator_class=Locator,
            solver=mock.Mock(),
        )

        wrapper = example_ui_wrapper(
            target="dummy", registries=[registry1, registry2]
        )

        # when
        stream = io.StringIO()
        with mock.patch("sys.stdout", stream):
            wrapper.help()

        # then
        self.assertEqual(
            stream.getvalue(),
            textwrap.dedent(
                f"""\
                Interactions
                ------------
                {Action!r}
                    Say hello.
                    Say bye.

                Locations
                ---------
                {Locator!r}
                    Return anything you like.
                    Good day!

            """
            ),
        )

    def test_help_message_priority_interactions(self):
        # The first registry in the list has the highest priority
        # The last registry in the list has the least priority

        high_priority_registry = StubRegistry(
            supported_locator_classes=[str],
            supported_interaction_classes=[float],
            interaction_doc="Interaction: I get a higher priority.",
            location_doc="Location: I get a higher priority.",
        )

        low_priority_registry = StubRegistry(
            supported_locator_classes=[str],
            supported_interaction_classes=[float],
            interaction_doc="Interaction: I get a lower priority.",
            location_doc="Location: I get a lower priority.",
        )

        # Put higher priority registry first.
        wrapper = example_ui_wrapper(
            target="dummy",
            registries=[high_priority_registry, low_priority_registry],
        )

        # when
        stream = io.StringIO()
        with mock.patch("sys.stdout", stream):
            wrapper.help()

        # then
        self.assertEqual(
            stream.getvalue(),
            textwrap.dedent(
                f"""\
                Interactions
                ------------
                {float!r}
                    Interaction: I get a higher priority.

                Locations
                ---------
                {str!r}
                    Location: I get a higher priority.

            """
            ),
        )

    def test_help_message_nothing_is_supported(self):
        registry = TargetRegistry()
        wrapper = example_ui_wrapper(registries=[registry])

        # when
        stream = io.StringIO()
        with mock.patch("sys.stdout", stream):
            wrapper.help()

        # then
        self.assertEqual(
            stream.getvalue(),
            textwrap.dedent(
                """\
                Interactions
                ------------
                No interactions are supported.

                Locations
                ---------
                No locations are supported.

            """
            ),
        )


class NumberHasTraits(HasTraits):
    number = Int()


@requires_toolkit([ToolkitName.qt, ToolkitName.wx])
class TestUIWrapperEventProcessed(unittest.TestCase, UnittestTools):
    """Test GUI events are processed and exceptions from the GUI event
    loop are handled.
    """

    def test_event_processed(self):
        # Test GUI events are processed such that the trait is changed.
        gui = GUI()
        model = NumberHasTraits()

        def handler(wrapper, action):
            gui.set_trait_later(model, "number", 2)

        wrapper = example_ui_wrapper(
            registries=[
                StubRegistry(
                    handler=handler,
                    supported_interaction_classes=[float],
                ),
            ],
        )

        with self.assertTraitChanges(model, "number"):
            wrapper.perform(2.123)

    def test_event_processed_prior_to_resolving_location(self):
        # Test GUI events are processed prior to resolving location
        gui = GUI()
        model = NumberHasTraits()
        gui.set_trait_later(model, "number", 2)

        def solver(wrapper, location):
            return model.number

        wrapper = example_ui_wrapper(
            registries=[
                StubRegistry(
                    solver=solver,
                    supported_locator_classes=[float],
                )
            ],
        )

        new_wrapper = wrapper.locate(4.567)
        self.assertEqual(new_wrapper._target, 2)

    def test_event_processed_with_exception_captured(self):
        # Test exceptions in the GUI event loop are captured and then cause
        # the test to error.
        gui = GUI()

        def raise_error():
            raise ZeroDivisionError()

        def handler(wrapper, action):
            gui.invoke_later(raise_error)

        wrapper = example_ui_wrapper(
            registries=[
                StubRegistry(
                    handler=handler,
                    supported_interaction_classes=[float],
                ),
            ],
        )
        with self.assertRaises(RuntimeError), self.assertLogs("traitsui"):
            wrapper.perform(1.234)

    def test_exception_not_in_gui(self):
        # Exceptions from code executed outside of the event loop are
        # propagated as is.

        def handler(wrapper, action):
            raise ZeroDivisionError()

        wrapper = example_ui_wrapper(
            registries=[
                StubRegistry(
                    handler=handler,
                    supported_interaction_classes=[float],
                ),
            ],
        )

        with self.assertRaises(ZeroDivisionError):
            wrapper.perform(9.99)

    def test_perform_event_processed_optional(self):
        # Allow event processing to be switched off.
        gui = GUI()
        side_effect = mock.Mock()

        def handler(wrapper, action):
            gui.invoke_later(side_effect)

        wrapper = example_ui_wrapper(
            registries=[
                StubRegistry(
                    handler=handler,
                    supported_interaction_classes=[float],
                ),
            ],
            auto_process_events=False,
        )

        # With auto_process_events set to False, events are not automatically
        # processed.
        wrapper.perform(12.345)
        self.addCleanup(process_cascade_events)

        self.assertEqual(side_effect.call_count, 0)

    def test_locate_event_processed_optional(self):
        # Allow event processing to be switched off.
        gui = GUI()
        side_effect = mock.Mock()
        gui.invoke_later(side_effect)
        self.addCleanup(process_cascade_events)

        def solver(wrapper, location):
            return 1

        wrapper = example_ui_wrapper(
            registries=[
                StubRegistry(
                    solver=solver,
                    supported_locator_classes=[float],
                ),
            ],
            auto_process_events=False,
        )

        # With auto_process_events set to False, events are not automatically
        # processed.
        new_wrapper = wrapper.locate(1.234)

        self.assertEqual(side_effect.call_count, 0)
        self.assertFalse(new_wrapper._auto_process_events)