This file is indexed.

/usr/lib/python3/dist-packages/unity8/shell/tests/test_notifications.py is in unity8-autopilot 8.12+16.04.20160401-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# Unity Autopilot Test Suite
# Copyright (C) 2012, 2013, 2014, 2015 Canonical
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

"""Tests for Notifications"""

import time
import os
import logging
import signal
import subprocess

from autopilot.matchers import Eventually
from gi.repository import Notify
from testtools.matchers import Equals, NotEquals
from ubuntuuitoolkit import ubuntu_scenarios

from unity8 import shell
from unity8.process_helpers import unlock_unity
from unity8.shell.tests import UnityTestCase


logger = logging.getLogger(__name__)


class NotificationsBase(UnityTestCase):
    """Base class for all notification tests that provides helper methods."""

    scenarios = ubuntu_scenarios.get_device_simulation_scenarios(
        ubuntu_scenarios.NEXUS4_DEVICE)

    def _get_icon_path(self, icon_name):
        """Given an icons file name returns the full path (either system or
        source tree.

        Consider the graphics directory as root so for example (running tests
        from installed unity8-autopilot package):
        >>> self.get_icon_path('clock.png')
        /usr/share/unity8/graphics/clock.png

        >>> self.get_icon_path('applicationIcons/facebook.png')
        /usr/share/unity8/graphics/applicationIcons/facebook.png

        """
        if os.path.abspath(__file__).startswith('/usr/'):
            return '/usr/share/unity8/graphics/' + icon_name
        else:
            return os.path.dirname(__file__) + (
                "/../../../../../tests/graphics/" + icon_name)

    def _get_notifications_list(self):
        return self.main_window.select_single(
            "Notifications",
            objectName='notificationList'
        )

    def _assert_notification(
        self,
        notification,
        summary=None,
        body=None,
        icon=True,
        secondary_icon=False,
        opacity=None
    ):
        """Assert that the expected qualities of a notification are as
        expected.

        """

        if summary is not None:
            self.assertThat(notification.summary, Eventually(Equals(summary)))

        if body is not None:
            self.assertThat(notification.body, Eventually(Equals(body)))

        if icon:
            self.assertThat(notification.iconSource, Eventually(NotEquals("")))
        else:
            self.assertThat(notification.iconSource, Eventually(Equals("")))

        if secondary_icon:
            self.assertThat(
                notification.secondaryIconSource,
                Eventually(NotEquals(""))
            )
        else:
            self.assertThat(
                notification.secondaryIconSource,
                Eventually(Equals(""))
            )

        if opacity is not None:
            self.assertThat(notification.opacity, Eventually(Equals(opacity)))


class InteractiveNotificationBase(NotificationsBase):
    """Collection of test for Interactive tests including snap decisions."""

    def setUp(self):
        super().setUp()
        # Need to keep track when we launch the notification script.
        self._notify_proc = None

    def test_interactive(self):
        """Interactive notification must react upon click on itself."""
        self.launch_unity()
        unlock_unity()

        notify_list = self._get_notifications_list()

        summary = "Interactive notification"
        body = "This notification can be clicked on to trigger an action."
        icon_path = self._get_icon_path('avatars/anna_olsson.png')
        actions = [("action_id", "dummy")]
        hints = [
            ("x-canonical-switch-to-application", "true"),
            ("x-canonical-secondary-icon", "dialer")
        ]

        self._create_interactive_notification(
            summary,
            body,
            icon_path,
            "NORMAL",
            actions,
            hints,
        )

        get_notification = lambda: notify_list.wait_select_single(
            'Notification', objectName='notification1')
        notification = get_notification()

        notification.pointing_device.click_object(
            notification.select_single(objectName="interactiveArea")
        )

        self.assert_notification_action_id_was_called('action_id')

    def test_sd_one_over_two_layout(self):
        """Snap-decision with three actions should use
           one-over two button layout.
        """
        self.launch_unity()
        unlock_unity()

        summary = "Theatre at Ferria Stadium"
        body = "at Ferria Stadium in Bilbao, Spain\n07578545317"
        hints = [
            ("x-canonical-snap-decisions", "true"),
            ("x-canonical-non-shaped-icon", "true"),
            ("x-canonical-private-affirmative-tint", "true")
        ]

        actions = [
            ('action_accept', 'Ok'),
            ('action_decline_1', 'Snooze'),
            ('action_decline_2', 'View'),
        ]

        self._create_interactive_notification(
            summary,
            body,
            None,
            "NORMAL",
            actions,
            hints
        )

        # verify and interact with the triggered snap-decision notification
        notify_list = self._get_notifications_list()
        get_notification = lambda: notify_list.wait_select_single(
            'Notification', objectName='notification1')
        notification = get_notification()
        self._assert_notification(
            notification, summary, body, False, False, 1.0)
        notification.pointing_device.click_object(
            notification.select_single(objectName="notify_oot_button0"))
        self.assert_notification_action_id_was_called("action_accept")

    def test_modal_sd_without_greeter(self):
        """Snap-decision should block input to shell
           without greeter/lockscreen.
        """
        self.launch_unity()
        unlock_unity()

        summary = "Incoming file"
        body = "Frank would like to send you the file: essay.pdf"
        icon_path = "sync-idle"
        hints = [
            ("x-canonical-snap-decisions", "true"),
            ("x-canonical-non-shaped-icon", "true"),
            ("x-canonical-private-affirmative-tint", "true"),
            ("x-canonical-private-rejection-tint", "true"),
        ]

        actions = [
            ('action_accept', 'Accept'),
            ('action_decline_1', 'Decline'),
        ]

        self._create_interactive_notification(
            summary,
            body,
            icon_path,
            "NORMAL",
            actions,
            hints
        )

        # verify that we cannot reveal the launcher (no longer interact with
        # the shell)
        time.sleep(1)
        self.main_window.show_dash_swiping()
        self.assertThat(
            self.main_window.is_launcher_open, Eventually(Equals(False)))

        # verify and interact with the triggered snap-decision notification
        notify_list = self._get_notifications_list()
        get_notification = lambda: notify_list.wait_select_single(
            'Notification', objectName='notification1')
        notification = get_notification()
        self._assert_notification(
            notification, summary, body, True, False, 1.0)
        notification.pointing_device.click_object(
            notification.select_single(objectName="notify_button0"))
        self.assert_notification_action_id_was_called("action_accept")

    def test_modal_sd_with_greeter(self):
        """A snap-decision should block input to the
           greeter/lockscreen beneath it.
        """
        self.launch_unity()

        summary = "Incoming file"
        body = "Frank would like to send you the file: essay.pdf"
        icon_path = "sync-idle"
        hints = [
            ("x-canonical-snap-decisions", "true"),
            ("x-canonical-non-shaped-icon", "true"),
            ("x-canonical-private-affirmative-tint", "true"),
            ("x-canonical-private-rejection-tint", "true"),
        ]

        actions = [
            ('action_accept', 'Accept'),
            ('action_decline_1', 'Decline'),
        ]

        self._create_interactive_notification(
            summary,
            body,
            icon_path,
            "NORMAL",
            actions,
            hints
        )

        # verify that we cannot reveal the launcher (no longer interact with
        # the shell)
        time.sleep(1)
        self.main_window.show_dash_swiping()
        self.assertThat(
            self.main_window.is_launcher_open, Eventually(Equals(False)))

        # verify and interact with the triggered snap-decision notification
        notify_list = self._get_notifications_list()
        get_notification = lambda: notify_list.wait_select_single(
            'Notification', objectName='notification1')
        notification = get_notification()
        self._assert_notification(
            notification, summary, body, True, False, 1.0)
        notification.pointing_device.click_object(
            notification.select_single(objectName="notify_button0"))
        self.assert_notification_action_id_was_called("action_accept")

    def _create_interactive_notification(
        self,
        summary="",
        body="",
        icon=None,
        urgency="NORMAL",
        actions=[],
        hints=[]
    ):
        """Create a interactive notification command.

        :param summary: Summary text for the notification
        :param body: Body text to display in the notification
        :param icon: Path string to the icon to use
        :param urgency: Urgency string for the noticiation, either: 'LOW',
            'NORMAL', 'CRITICAL'
        :param actions: List of tuples containing the 'id' and 'label' for all
            the actions to add
        :param hint_strings: List of tuples containing the 'name' and value for
            setting the hint strings for the notification

        """

        logger.info(
            "Creating snap-decision notification with summary(%s), body(%s) "
            "and urgency(%r)",
            summary,
            body,
            urgency
        )

        script_args = [
            '--summary', summary,
            '--body', body,
            '--urgency', urgency
        ]

        if icon is not None:
            script_args.extend(['--icon', icon])

        for hint in hints:
            key, value = hint
            script_args.extend(['--hint', "%s,%s" % (key, value)])

        for action in actions:
            action_id, action_label = action
            action_string = "%s,%s" % (action_id, action_label)
            script_args.extend(['--action', action_string])

        python_bin = subprocess.check_output(['which', 'python3']).strip()
        command = [python_bin, self._get_notify_script()] + script_args
        logger.info("Launching snap-decision notification as: %s", command)
        self._notify_proc = subprocess.Popen(
            command,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            close_fds=True,
            universal_newlines=True,
        )

        self.addCleanup(self._tidy_up_script_process)

        poll_result = self._notify_proc.poll()
        if poll_result is not None and self._notify_proc.returncode != 0:
            error_output = self._notify_proc.communicate()[1]
            raise RuntimeError("Call to script failed with: %s" % error_output)

    def _get_notify_script(self):
        """Returns the path to the interactive notification
           creation script.
        """
        file_path = "../../create_interactive_notification.py"

        the_path = os.path.abspath(
            os.path.join(__file__, file_path))

        return the_path

    def _tidy_up_script_process(self):
        if self._notify_proc is not None and self._notify_proc.poll() is None:
            logger.error("Notification process wasn't killed, killing now.")
            os.killpg(self._notify_proc.pid, signal.SIGTERM)

    def assert_notification_action_id_was_called(self, action_id, timeout=10):
        """Assert that the interactive notification callback of id *action_id*
        was called.

        :raises AssertionError: If no interactive notification has actually
            been created.
        :raises AssertionError: When *action_id* does not match the actual
            returned.
        :raises AssertionError: If no callback was called at all.
        """

        if self._notify_proc is None:
            raise AssertionError("No interactive notification was created.")

        for i in range(timeout):
            self._notify_proc.poll()
            if self._notify_proc.returncode is not None:
                output = self._notify_proc.communicate()
                actual_action_id = output[0].strip("\n")
                if actual_action_id != action_id:
                    raise AssertionError(
                        "action id '%s' does not match actual returned '%s'"
                        % (action_id, actual_action_id)
                    )
                else:
                    return
            time.sleep(1)

        os.killpg(self._notify_proc.pid, signal.SIGTERM)
        self._notify_proc = None
        raise AssertionError(
            "No callback was called, killing interactivenotification script"
        )


class EphemeralNotificationsTests(NotificationsBase):
    """Collection of tests for Emphemeral notifications (non-interactive.)"""

    def setUp(self):
        super().setUp()
        # Because we are using the Notify library we need to init and un-init
        # otherwise we get crashes.
        Notify.init("Autopilot Ephemeral Notification Tests")
        self.addCleanup(Notify.uninit)

    def test_icon_summary_body(self):
        """Notification must display the expected summary and body text."""
        self.launch_unity()
        unlock_unity()

        notify_list = self._get_notifications_list()

        summary = "Icon-Summary-Body"
        body = "Hey pal, what's up with the party next weekend? Will you " \
               "join me and Anna?"
        icon_path = self._get_icon_path('avatars/anna_olsson.png')
        hints = [
            ("x-canonical-secondary-icon", "message")
        ]

        notification = shell.create_ephemeral_notification(
            summary,
            body,
            icon_path,
            hints,
            "NORMAL",
        )

        notification.show()

        notification = lambda: notify_list.wait_select_single(
            'Notification', objectName='notification1')
        self._assert_notification(
            notification(),
            summary,
            body,
            True,
            True,
            1.0,
        )

    def test_icon_summary(self):
        """Notification must display the expected summary and secondary
        icon."""
        self.launch_unity()
        unlock_unity()

        notify_list = self._get_notifications_list()

        summary = "Upload of image completed"
        icon_path = self._get_icon_path('applicationIcons/facebook.png')
        hints = []

        notification = shell.create_ephemeral_notification(
            summary,
            None,
            icon_path,
            hints,
            "NORMAL",
        )

        notification.show()

        notification = lambda: notify_list.wait_select_single(
            'Notification', objectName='notification1')
        self._assert_notification(
            notification(),
            summary,
            None,
            True,
            False,
            1.0
        )

    def test_urgency_order(self):
        """Notifications must be displayed in order according to their
        urgency."""
        self.launch_unity()
        unlock_unity()

        notify_list = self._get_notifications_list()

        summary_low = 'Low Urgency'
        body_low = "No, I'd rather see paint dry, pal *yawn*"
        icon_path_low = self._get_icon_path('avatars/amanda.png')

        summary_normal = 'Normal Urgency'
        body_normal = "Hey pal, what's up with the party next weekend? Will " \
            "you join me and Anna?"
        icon_path_normal = self._get_icon_path('avatars/funky.png')

        summary_critical = 'Critical Urgency'
        body_critical = 'Dude, this is so urgent you have no idea :)'
        icon_path_critical = self._get_icon_path('avatars/anna_olsson.png')

        notification_normal = shell.create_ephemeral_notification(
            summary_normal,
            body_normal,
            icon_path_normal,
            urgency="NORMAL"
        )
        notification_normal.show()

        notification_low = shell.create_ephemeral_notification(
            summary_low,
            body_low,
            icon_path_low,
            urgency="LOW"
        )
        notification_low.show()

        notification_critical = shell.create_ephemeral_notification(
            summary_critical,
            body_critical,
            icon_path_critical,
            urgency="CRITICAL"
        )
        notification_critical.show()

        get_notification = lambda: notify_list.wait_select_single(
            'Notification',
            summary=summary_critical
        )

        notification = get_notification()
        self._assert_notification(
            notification,
            summary_critical,
            body_critical,
            True,
            False,
            1.0
        )

        get_normal_notification = lambda: notify_list.wait_select_single(
            'Notification',
            summary=summary_normal
        )
        notification = get_normal_notification()
        self._assert_notification(
            notification,
            summary_normal,
            body_normal,
            True,
            False,
            1.0
        )

        get_low_notification = lambda: notify_list.wait_select_single(
            'Notification',
            summary=summary_low
        )
        notification = get_low_notification()
        self._assert_notification(
            notification,
            summary_low,
            body_low,
            True,
            False,
            1.0
        )

    def test_summary_and_body(self):
        """Notification must display the expected summary- and body-text."""
        self.launch_unity()
        unlock_unity()

        notify_list = self._get_notifications_list()

        summary = 'Summary-Body'
        body = 'This is a superfluous notification'

        notification = shell.create_ephemeral_notification(summary, body)
        notification.show()

        notification = notify_list.wait_select_single(
            'Notification', objectName='notification1')

        self._assert_notification(
            notification,
            summary,
            body,
            False,
            False,
            1.0
        )

    def test_summary_only(self):
        """Notification must display only the expected summary-text."""
        self.launch_unity()
        unlock_unity()

        notify_list = self._get_notifications_list()

        summary = 'Summary-Only'

        notification = shell.create_ephemeral_notification(summary)
        notification.show()

        notification = notify_list.wait_select_single(
            'Notification', objectName='notification1')

        self._assert_notification(notification, summary, '', False, False, 1.0)

    def test_update_notification_same_layout(self):
        """Notification must allow updating its contents while being
        displayed."""
        self.launch_unity()
        unlock_unity()

        notify_list = self._get_notifications_list()

        summary = 'Initial notification'
        body = 'This is the original content of this notification-bubble.'
        icon_path = self._get_icon_path('avatars/funky.png')

        notification = shell.create_ephemeral_notification(
            summary,
            body,
            icon_path
        )
        notification.show()

        get_notification = lambda: notify_list.wait_select_single(
            'Notification', summary=summary)
        self._assert_notification(
            get_notification(),
            summary,
            body,
            True,
            False,
            1.0
        )

        summary = 'Updated notification'
        body = 'Here the same bubble with new title- and body-text, even ' \
            'the icon can be changed on the update.'
        icon_path = self._get_icon_path('avatars/amanda.png')
        notification.update(summary, body, icon_path)
        notification.show()
        self._assert_notification(
            get_notification(), summary, body, True, False, 1.0)

    def test_update_notification_layout_change(self):
        """Notification must allow updating its contents and layout while
        being displayed."""
        self.launch_unity()
        unlock_unity()

        notify_list = self._get_notifications_list()

        summary = 'Initial layout'
        body = 'This bubble uses the icon-title-body layout with a ' \
            'secondary icon.'
        icon_path = self._get_icon_path('avatars/anna_olsson.png')
        hint_icon = 'dialer'

        notification = shell.create_ephemeral_notification(
            summary,
            body,
            icon_path
        )
        notification.set_hint_string(
            'x-canonical-secondary-icon',
            hint_icon
        )
        notification.show()

        get_notification = lambda: notify_list.wait_select_single(
            'Notification', objectName='notification1')

        self._assert_notification(
            get_notification(),
            summary,
            body,
            True,
            True,
            1.0
        )

        notification.clear_hints()
        summary = 'Updated layout'
        body = 'After the update we now have a bubble using the title-body ' \
            'layout.'
        notification.update(summary, body, None)
        notification.show()

        self.assertThat(get_notification, Eventually(NotEquals(None)))
        self._assert_notification(
            get_notification(), summary, body, False, False, 1.0)

    def test_notification_helper(self):
        """ use the create notification script to get a notification dialog.
        Check that the arguments passed to the script match the fields. """

        self.launch_unity()
        unlock_unity()

        summary = 'Helper summary'
        body = 'Helper body'

        notification = shell.create_ephemeral_notification(summary, body)
        notification.show()

        notification_data = self.main_window.wait_for_notification()

        self.assertThat(notification_data['summary'],
                        Eventually(Equals(summary)))
        self.assertThat(notification_data['body'], Eventually(Equals(body)))