This file is indexed.

/usr/lib/python3/dist-packages/autopilot/tests/unit/test_input.py is in python3-autopilot-tests 1.4+14.04.20140416-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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# Autopilot Functional Test Tool
# Copyright (C) 2013, 2014 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/>.
#

import testscenarios
from evdev import ecodes, uinput
from mock import ANY, call, Mock, patch
from testtools import TestCase
from testtools.matchers import Contains, raises

import autopilot.input
from autopilot import utilities
from autopilot.input import _uinput
from autopilot.input._common import get_center_point


class Empty(object):

    def __repr__(self):
        return "<Empty>"


def make_fake_object(globalRect=False, center=False, xywh=False):
    obj = Empty()
    if globalRect:
        obj.globalRect = (0, 0, 100, 100)
    if center:
        obj.center_x = 123
        obj.center_y = 345
    if xywh:
        obj.x, obj.y, obj.w, obj.h = (100, 100, 20, 40)
    return obj


class InputCenterPointTests(TestCase):
    """Tests for the input get_center_point utility."""

    def test_get_center_point_raises_ValueError_on_empty_object(self):
        obj = make_fake_object()
        fn = lambda: get_center_point(obj)
        expected_exception = ValueError(
            "Object '%r' does not have any recognised position attributes" %
            obj)
        self.assertThat(fn, raises(expected_exception))

    def test_get_center_point_works_with_globalRect(self):
        obj = make_fake_object(globalRect=True)
        x, y = get_center_point(obj)

        self.assertEqual(50, x)
        self.assertEqual(50, y)

    def test_raises_ValueError_on_uniterable_globalRect(self):
        obj = Empty()
        obj.globalRect = 123
        expected_exception = ValueError(
            "Object '<Empty>' has globalRect attribute, but it is not of the "
            "correct type"
        )
        self.assertThat(
            lambda: get_center_point(obj),
            raises(expected_exception)
        )

    def test_raises_ValueError_on_too_small_globalRect(self):
        obj = Empty()
        obj.globalRect = (1, 2, 3)
        expected_exception = ValueError(
            "Object '<Empty>' has globalRect attribute, but it is not of the "
            "correct type"
        )
        self.assertThat(
            lambda: get_center_point(obj),
            raises(expected_exception)
        )

    @patch('autopilot.input._common._logger')
    def test_get_center_point_logs_with_globalRect(self, mock_logger):
        obj = make_fake_object(globalRect=True)
        x, y = get_center_point(obj)

        mock_logger.debug.assert_called_once_with(
            "Moving to object's globalRect coordinates."
        )

    def test_get_center_point_works_with_center_points(self):
        obj = make_fake_object(center=True)
        x, y = get_center_point(obj)

        self.assertEqual(123, x)
        self.assertEqual(345, y)

    @patch('autopilot.input._common._logger')
    def test_get_center_point_logs_with_center_points(self, mock_logger):
        obj = make_fake_object(center=True)
        x, y = get_center_point(obj)

        mock_logger.debug.assert_called_once_with(
            "Moving to object's center_x, center_y coordinates."
        )

    def test_get_center_point_works_with_xywh(self):
        obj = make_fake_object(xywh=True)
        x, y = get_center_point(obj)

        self.assertEqual(110, x)
        self.assertEqual(120, y)

    @patch('autopilot.input._common._logger')
    def test_get_center_point_logs_with_xywh(self, mock_logger):
        obj = make_fake_object(xywh=True)
        x, y = get_center_point(obj)

        mock_logger.debug.assert_called_once_with(
            "Moving to object's center point calculated from x,y,w,h "
            "attributes."
        )

    def test_get_center_point_raises_valueError_on_non_numerics(self):
        obj = Empty()
        obj.x, obj.y, obj.w, obj.h = 1, None, True, "oof"
        expected_exception = ValueError(
            "Object '<Empty>' has x,y attribute, but they are not of the "
            "correct type"
        )
        self.assertThat(
            lambda: get_center_point(obj),
            raises(expected_exception)
        )

    def test_get_center_point_prefers_globalRect(self):
        obj = make_fake_object(globalRect=True, center=True, xywh=True)
        x, y = get_center_point(obj)

        self.assertEqual(50, x)
        self.assertEqual(50, y)

    def test_get_center_point_prefers_center_points(self):
        obj = make_fake_object(globalRect=False, center=True, xywh=True)
        x, y = get_center_point(obj)

        self.assertEqual(123, x)
        self.assertEqual(345, y)


class UInputTestCase(TestCase):
    """Tests for the global methods of the uinput module."""

    def test_create_touch_device_must_print_deprecation_message(self):
        with patch('autopilot.utilities.logger') as patched_log:
            with patch('autopilot.input._uinput.UInput'):
                _uinput.create_touch_device('dummy', 'dummy')
        self.assertThat(
            patched_log.warning.call_args[0][0],
            Contains(
                "This function is deprecated. Please use 'the Touch class to "
                "instantiate a device object' instead."
            )
        )


class UInputKeyboardDeviceTestCase(TestCase):
    """Test the integration with evdev.UInput for the keyboard."""

    _PRESS_VALUE = 1
    _RELEASE_VALUE = 0

    def get_keyboard_with_mocked_backend(self):
        keyboard = _uinput._UInputKeyboardDevice(device_class=Mock)
        keyboard._device.mock_add_spec(uinput.UInput, spec_set=True)
        return keyboard

    def assert_key_press_emitted_write_and_syn(self, keyboard, key):
        self.assert_emitted_write_and_syn(keyboard, key, self._PRESS_VALUE)

    def assert_key_release_emitted_write_and_syn(self, keyboard, key):
        self.assert_emitted_write_and_syn(keyboard, key, self._RELEASE_VALUE)

    def assert_emitted_write_and_syn(self, keyboard, key, value):
        key_ecode = ecodes.ecodes.get(key)
        expected_calls = [
            call.write(ecodes.EV_KEY, key_ecode, value),
            call.syn()
        ]

        self.assertEqual(expected_calls, keyboard._device.mock_calls)

    def press_key_and_reset_mock(self, keyboard, key):
        keyboard.press(key)
        keyboard._device.reset_mock()

    def test_press_key_must_emit_write_and_syn(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        keyboard.press('KEY_A')
        self.assert_key_press_emitted_write_and_syn(keyboard, 'KEY_A')

    def test_press_key_must_append_leading_string(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        keyboard.press('A')
        self.assert_key_press_emitted_write_and_syn(keyboard, 'KEY_A')

    def test_press_key_must_ignore_case(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        keyboard.press('a')
        self.assert_key_press_emitted_write_and_syn(keyboard, 'KEY_A')

    def test_press_unexisting_key_must_raise_error(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        error = self.assertRaises(
            ValueError, keyboard.press, 'unexisting')

        self.assertEqual('Unknown key name: unexisting.', str(error))

    def test_release_not_pressed_key_must_raise_error(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        error = self.assertRaises(
            ValueError, keyboard.release, 'A')

        self.assertEqual("Key 'A' not pressed.", str(error))

    def test_release_key_must_emit_write_and_syn(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        self.press_key_and_reset_mock(keyboard, 'KEY_A')

        keyboard.release('KEY_A')
        self.assert_key_release_emitted_write_and_syn(keyboard, 'KEY_A')

    def test_release_key_must_append_leading_string(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        self.press_key_and_reset_mock(keyboard, 'KEY_A')

        keyboard.release('A')
        self.assert_key_release_emitted_write_and_syn(keyboard, 'KEY_A')

    def test_release_key_must_ignore_case(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        self.press_key_and_reset_mock(keyboard, 'KEY_A')

        keyboard.release('a')
        self.assert_key_release_emitted_write_and_syn(keyboard, 'KEY_A')

    def test_release_unexisting_key_must_raise_error(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        error = self.assertRaises(
            ValueError, keyboard.release, 'unexisting')

        self.assertEqual('Unknown key name: unexisting.', str(error))

    def test_release_pressed_keys_without_pressed_keys_must_do_nothing(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        keyboard.release_pressed_keys()
        self.assertEqual([], keyboard._device.mock_calls)

    def test_release_pressed_keys_with_pressed_keys(self):
        expected_calls = [
            call.write(
                ecodes.EV_KEY, ecodes.ecodes.get('KEY_A'),
                self._RELEASE_VALUE),
            call.syn(),
            call.write(
                ecodes.EV_KEY, ecodes.ecodes.get('KEY_B'),
                self._RELEASE_VALUE),
            call.syn()
        ]

        keyboard = self.get_keyboard_with_mocked_backend()
        self.press_key_and_reset_mock(keyboard, 'KEY_A')
        self.press_key_and_reset_mock(keyboard, 'KEY_B')

        keyboard.release_pressed_keys()

        self.assertEqual(expected_calls, keyboard._device.mock_calls)

    def test_release_pressed_keys_already_released(self):
        expected_calls = []
        keyboard = self.get_keyboard_with_mocked_backend()
        keyboard.press('KEY_A')
        keyboard.release_pressed_keys()
        keyboard._device.reset_mock()

        keyboard.release_pressed_keys()
        self.assertEqual(expected_calls, keyboard._device.mock_calls)


class UInputKeyboardTestCase(testscenarios.TestWithScenarios, TestCase):
    """Test UInput Keyboard helper for autopilot tests."""

    scenarios = [
        ('single key', dict(keys='a', expected_calls_args=['a'])),
        ('upper-case letter', dict(
            keys='A', expected_calls_args=['KEY_LEFTSHIFT', 'A'])),
        ('key combination', dict(
            keys='a+b', expected_calls_args=['a', 'b']))
    ]

    def setUp(self):
        super(UInputKeyboardTestCase, self).setUp()
        # Return to the original device after the test.
        self.addCleanup(self.set_keyboard_device, _uinput.Keyboard._device)
        # Mock the sleeps so we don't have to spend time actually sleeping.
        self.addCleanup(utilities.sleep.disable_mock)
        utilities.sleep.enable_mock()

    def set_keyboard_device(self, device):
        _uinput.Keyboard._device = device

    def get_keyboard_with_mocked_backend(self):
        _uinput.Keyboard._device = None
        keyboard = _uinput.Keyboard(device_class=Mock)
        keyboard._device.mock_add_spec(
            _uinput._UInputKeyboardDevice, spec_set=True)
        return keyboard

    def test_press_must_put_press_device_keys(self):
        expected_calls = [
            call.press(arg) for arg in self.expected_calls_args]
        keyboard = self.get_keyboard_with_mocked_backend()
        keyboard.press(self.keys)

        self.assertEqual(expected_calls, keyboard._device.mock_calls)

    def test_release_must_release_device_keys(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        keyboard.press(self.keys)
        keyboard._device.reset_mock()

        expected_calls = [
            call.release(arg) for arg in
            reversed(self.expected_calls_args)]
        keyboard.release(self.keys)

        self.assertEqual(
            expected_calls, keyboard._device.mock_calls)

    def test_press_and_release_must_press_device_keys(self):
        expected_press_calls = [
            call.press(arg) for arg in self.expected_calls_args]
        ignored_calls = [
            ANY for arg in self.expected_calls_args]

        keyboard = self.get_keyboard_with_mocked_backend()
        keyboard.press_and_release(self.keys)

        self.assertEqual(
            expected_press_calls + ignored_calls,
            keyboard._device.mock_calls)

    def test_press_and_release_must_release_device_keys_in_reverse_order(
            self):
        ignored_calls = [
            ANY for arg in self.expected_calls_args]
        expected_release_calls = [
            call.release(arg) for arg in
            reversed(self.expected_calls_args)]

        keyboard = self.get_keyboard_with_mocked_backend()
        keyboard.press_and_release(self.keys)

        self.assertEqual(
            ignored_calls + expected_release_calls,
            keyboard._device.mock_calls)

    def test_on_test_end_without_device_must_do_nothing(self):
        _uinput.Keyboard._device = None
        # This will fail if it calls anything from the device, as it's None.
        _uinput.Keyboard.on_test_end(self)

    def test_on_test_end_with_device_must_release_pressed_keys(self):
        keyboard = self.get_keyboard_with_mocked_backend()
        _uinput.Keyboard.on_test_end(self)
        self.assertEqual(
            [call.release_pressed_keys()], keyboard._device.mock_calls)


class TouchEventsTestCase(TestCase):

    def assert_expected_ev_abs(self, res_x, res_y, actual_ev_abs):
        expected_ev_abs = [
            (ecodes.ABS_X, (0, res_x, 0, 0)),
            (ecodes.ABS_Y, (0, res_y, 0, 0)),
            (ecodes.ABS_PRESSURE, (0, 65535, 0, 0)),
            (ecodes.ABS_MT_POSITION_X, (0, res_x, 0, 0)),
            (ecodes.ABS_MT_POSITION_Y, (0, res_y, 0, 0)),
            (ecodes.ABS_MT_TOUCH_MAJOR, (0, 30, 0, 0)),
            (ecodes.ABS_MT_TRACKING_ID, (0, 65535, 0, 0)),
            (ecodes.ABS_MT_PRESSURE, (0, 255, 0, 0)),
            (ecodes.ABS_MT_SLOT, (0, 9, 0, 0))
        ]
        self.assertEqual(expected_ev_abs, actual_ev_abs)

    def test_get_touch_events_without_args_must_use_system_resolution(self):
        with patch.object(
                _uinput, '_get_system_resolution', spec_set=True,
                autospec=True) as mock_system_resolution:
            mock_system_resolution.return_value = (
                'system_res_x', 'system_res_y')
            events = _uinput._get_touch_events()

        ev_abs = events.get(ecodes.EV_ABS)
        self.assert_expected_ev_abs('system_res_x', 'system_res_y', ev_abs)

    def test_get_touch_events_with_args_must_use_given_resulution(self):
        events = _uinput._get_touch_events('given_res_x', 'given_res_y')
        ev_abs = events.get(ecodes.EV_ABS)
        self.assert_expected_ev_abs('given_res_x', 'given_res_y', ev_abs)


class UInputTouchDeviceTestCase(TestCase):
    """Test the integration with evdev.UInput for the touch device."""

    def setUp(self):
        super(UInputTouchDeviceTestCase, self).setUp()
        self._number_of_slots = 9

        # Return to the original device after the test.
        self.addCleanup(
            self.set_mouse_device,
            _uinput._UInputTouchDevice._device,
            _uinput._UInputTouchDevice._touch_fingers_in_use,
            _uinput._UInputTouchDevice._last_tracking_id)

        # Always start the tests without fingers in use.
        _uinput._UInputTouchDevice._touch_fingers_in_use = []
        _uinput._UInputTouchDevice._last_tracking_id = 0

    def set_mouse_device(
            self, device, touch_fingers_in_use, last_tracking_id):
        _uinput._UInputTouchDevice._device = device
        _uinput._UInputTouchDevice._touch_fingers_in_use = touch_fingers_in_use
        _uinput._UInputTouchDevice._last_tracking_id = last_tracking_id

    def get_touch_with_mocked_backend(self):
        dummy_x_resolution = 100
        dummy_y_resolution = 100

        _uinput._UInputTouchDevice._device = None
        touch = _uinput._UInputTouchDevice(
            res_x=dummy_x_resolution, res_y=dummy_y_resolution,
            device_class=Mock)
        touch._device.mock_add_spec(uinput.UInput, spec_set=True)
        return touch

    def assert_finger_down_emitted_write_and_syn(
            self, touch, slot, tracking_id, x, y):
        press_value = 1
        expected_calls = [
            call.write(ecodes.EV_ABS, ecodes.ABS_MT_SLOT, slot),
            call.write(
                ecodes.EV_ABS, ecodes.ABS_MT_TRACKING_ID, tracking_id),
            call.write(
                ecodes.EV_KEY, ecodes.BTN_TOOL_FINGER, press_value),
            call.write(ecodes.EV_ABS, ecodes.ABS_MT_POSITION_X, x),
            call.write(ecodes.EV_ABS, ecodes.ABS_MT_POSITION_Y, y),
            call.write(ecodes.EV_ABS, ecodes.ABS_MT_PRESSURE, 400),
            call.syn()
        ]
        self.assertEqual(expected_calls, touch._device.mock_calls)

    def assert_finger_move_emitted_write_and_syn(self, touch, slot, x, y):
        expected_calls = [
            call.write(ecodes.EV_ABS, ecodes.ABS_MT_SLOT, slot),
            call.write(ecodes.EV_ABS, ecodes.ABS_MT_POSITION_X, x),
            call.write(ecodes.EV_ABS, ecodes.ABS_MT_POSITION_Y, y),
            call.syn()
        ]
        self.assertEqual(expected_calls, touch._device.mock_calls)

    def assert_finger_up_emitted_write_and_syn(self, touch, slot):
        lift_tracking_id = -1
        release_value = 0
        expected_calls = [
            call.write(ecodes.EV_ABS, ecodes.ABS_MT_SLOT, slot),
            call.write(
                ecodes.EV_ABS, ecodes.ABS_MT_TRACKING_ID, lift_tracking_id),
            call.write(
                ecodes.EV_KEY, ecodes.BTN_TOOL_FINGER, release_value),
            call.syn()
        ]
        self.assertEqual(expected_calls, touch._device.mock_calls)

    def test_finger_down_must_use_free_slot(self):
        for slot in range(self._number_of_slots):
            touch = self.get_touch_with_mocked_backend()

            touch.finger_down(0, 0)

            self.assert_finger_down_emitted_write_and_syn(
                touch, slot=slot, tracking_id=ANY, x=0, y=0)

    def test_finger_down_without_free_slots_must_raise_error(self):
        # Claim all the available slots.
        for slot in range(self._number_of_slots):
            touch = self.get_touch_with_mocked_backend()
            touch.finger_down(0, 0)

        touch = self.get_touch_with_mocked_backend()

        # Try to use one more.
        error = self.assertRaises(RuntimeError, touch.finger_down, 11, 11)
        self.assertEqual(
            'All available fingers have been used already.', str(error))

    def test_finger_down_must_use_unique_tracking_id(self):
        for number in range(self._number_of_slots):
            touch = self.get_touch_with_mocked_backend()
            touch.finger_down(0, 0)

            self.assert_finger_down_emitted_write_and_syn(
                touch, slot=ANY, tracking_id=number + 1, x=0, y=0)

    def test_finger_down_must_not_reuse_tracking_ids(self):
        # Claim and release all the available slots once.
        for number in range(self._number_of_slots):
            touch = self.get_touch_with_mocked_backend()
            touch.finger_down(0, 0)
            touch.finger_up()

        touch = self.get_touch_with_mocked_backend()

        touch.finger_down(12, 12)
        self.assert_finger_down_emitted_write_and_syn(
            touch, slot=ANY, tracking_id=number + 2, x=12, y=12)

    def test_finger_down_with_finger_pressed_must_raise_error(self):
        touch = self.get_touch_with_mocked_backend()
        touch.finger_down(0, 0)

        error = self.assertRaises(RuntimeError, touch.finger_down, 0, 0)
        self.assertEqual(
            "Cannot press finger: it's already pressed.", str(error))

    def test_finger_move_without_finger_pressed_must_raise_error(self):
        touch = self.get_touch_with_mocked_backend()

        error = self.assertRaises(RuntimeError, touch.finger_move, 10, 10)
        self.assertEqual(
            'Attempting to move without finger being down.', str(error))

    def test_finger_move_must_use_assigned_slot(self):
        for slot in range(self._number_of_slots):
            touch = self.get_touch_with_mocked_backend()
            touch.finger_down(0, 0)
            touch._device.reset_mock()

            touch.finger_move(10, 10)

            self.assert_finger_move_emitted_write_and_syn(
                touch, slot=slot, x=10, y=10)

    def test_finger_move_must_reuse_assigned_slot(self):
        first_slot = 0
        touch = self.get_touch_with_mocked_backend()
        touch.finger_down(1, 1)
        touch._device.reset_mock()

        touch.finger_move(13, 13)
        self.assert_finger_move_emitted_write_and_syn(
            touch, slot=first_slot, x=13, y=13)
        touch._device.reset_mock()

        touch.finger_move(14, 14)
        self.assert_finger_move_emitted_write_and_syn(
            touch, slot=first_slot, x=14, y=14)

    def test_finger_up_without_finger_pressed_must_raise_error(self):
        touch = self.get_touch_with_mocked_backend()

        error = self.assertRaises(RuntimeError, touch.finger_up)
        self.assertEqual(
            "Cannot release finger: it's not pressed.", str(error))

    def test_finger_up_must_use_assigned_slot(self):
        fingers = []
        for slot in range(self._number_of_slots):
            touch = self.get_touch_with_mocked_backend()
            touch.finger_down(0, 0)
            touch._device.reset_mock()
            fingers.append(touch)

        for slot, touch in enumerate(fingers):
            touch.finger_up()

            self.assert_finger_up_emitted_write_and_syn(touch, slot=slot)
            touch._device.reset_mock()

    def test_finger_up_must_release_slot(self):
        fingers = []
        # Claim all the available slots.
        for slot in range(self._number_of_slots):
            touch = self.get_touch_with_mocked_backend()
            touch.finger_down(0, 0)
            fingers.append(touch)

        slot_to_reuse = 3
        fingers[slot_to_reuse].finger_up()

        touch = self.get_touch_with_mocked_backend()

        # Try to use one more.
        touch.finger_down(15, 15)
        self.assert_finger_down_emitted_write_and_syn(
            touch, slot=slot_to_reuse, tracking_id=ANY, x=15, y=15)

    def test_device_with_finger_down_must_be_pressed(self):
        touch = self.get_touch_with_mocked_backend()
        touch.finger_down(0, 0)

        self.assertTrue(touch.pressed)

    def test_device_without_finger_down_must_not_be_pressed(self):
        touch = self.get_touch_with_mocked_backend()
        self.assertFalse(touch.pressed)

    def test_device_after_finger_up_must_not_be_pressed(self):
        touch = self.get_touch_with_mocked_backend()
        touch.finger_down(0, 0)
        touch.finger_up()

        self.assertFalse(touch.pressed)

    def test_press_other_device_must_not_press_all_of_them(self):
        other_touch = self.get_touch_with_mocked_backend()
        other_touch.finger_down(0, 0)

        touch = self.get_touch_with_mocked_backend()
        self.assertFalse(touch.pressed)


class UInputTouchTestCase(TestCase):
    """Test UInput Touch helper for autopilot tests."""

    def setUp(self):
        super(UInputTouchTestCase, self).setUp()
        # Mock the sleeps so we don't have to spend time actually sleeping.
        self.addCleanup(utilities.sleep.disable_mock)
        utilities.sleep.enable_mock()

    def get_touch_with_mocked_backend(self):
        touch = _uinput.Touch(device_class=Mock)
        touch._device.mock_add_spec(
            _uinput._UInputTouchDevice, spec_set=True)
        return touch

    def test_tap_must_put_finger_down_and_then_up(self):
        expected_calls = [
            call.finger_down(0, 0),
            call.finger_up()
        ]

        touch = self.get_touch_with_mocked_backend()
        touch.tap(0, 0)
        self.assertEqual(expected_calls, touch._device.mock_calls)

    def test_tap_object_must_put_finger_down_and_then_up_on_the_center(self):
        object_ = type('Dummy', (object,), {'globalRect': (0, 0, 10, 10)})
        expected_calls = [
            call.finger_down(5, 5),
            call.finger_up()
        ]

        touch = self.get_touch_with_mocked_backend()
        touch.tap_object(object_)
        self.assertEqual(expected_calls, touch._device.mock_calls)

    def test_press_must_put_finger_down(self):
        expected_calls = [call.finger_down(0, 0)]

        touch = self.get_touch_with_mocked_backend()
        touch.press(0, 0)
        self.assertEqual(expected_calls, touch._device.mock_calls)

    def test_release_must_put_finger_up(self):
        expected_calls = [call.finger_up()]

        touch = self.get_touch_with_mocked_backend()
        touch.release()
        self.assertEqual(expected_calls, touch._device.mock_calls)

    def test_move_must_move_finger(self):
        expected_calls = [call.finger_move(10, 10)]

        touch = self.get_touch_with_mocked_backend()
        touch.move(10, 10)
        self.assertEqual(expected_calls, touch._device.mock_calls)

    def test_drag_must_call_finger_down_move_and_up(self):
        expected_calls = [
            call.finger_down(0, 0),
            call.finger_move(10, 10),
            call.finger_up()
        ]

        touch = self.get_touch_with_mocked_backend()
        touch.drag(0, 0, 10, 10)
        self.assertEqual(expected_calls, touch._device.mock_calls)

    def test_drag_must_move_with_specified_rate(self):
        expected_calls = [
            call.finger_down(0, 0),
            call.finger_move(5, 5),
            call.finger_move(10, 10),
            call.finger_move(15, 15),
            call.finger_up()]

        touch = self.get_touch_with_mocked_backend()
        touch.drag(0, 0, 15, 15, rate=5)

        self.assertEqual(
            expected_calls, touch._device.mock_calls)

    def test_drag_without_rate_must_use_default(self):
        expected_calls = [
            call.finger_down(0, 0),
            call.finger_move(10, 10),
            call.finger_move(20, 20),
            call.finger_up()]

        touch = self.get_touch_with_mocked_backend()
        touch.drag(0, 0, 20, 20)

        self.assertEqual(
            expected_calls, touch._device.mock_calls)

    def test_drag_to_same_place_must_not_move(self):
        expected_calls = [
            call.finger_down(0, 0),
            call.finger_up()
        ]

        touch = self.get_touch_with_mocked_backend()
        touch.drag(0, 0, 0, 0)
        self.assertEqual(expected_calls, touch._device.mock_calls)


class MultipleUInputTouchBackend(_uinput._UInputTouchDevice):

    def __init__(self, res_x=100, res_y=100, device_class=Mock):
        super(MultipleUInputTouchBackend, self).__init__(
            res_x, res_y, device_class)


class MultipleUInputTouchTestCase(TestCase):

    def setUp(self):
        super(MultipleUInputTouchTestCase, self).setUp()
        # Return to the original device after the test.
        self.addCleanup(
            self.set_mouse_device,
            _uinput._UInputTouchDevice._device,
            _uinput._UInputTouchDevice._touch_fingers_in_use,
            _uinput._UInputTouchDevice._last_tracking_id)

    def set_mouse_device(
            self, device, touch_fingers_in_use, last_tracking_id):
        _uinput._UInputTouchDevice._device = device
        _uinput._UInputTouchDevice._touch_fingers_in_use = touch_fingers_in_use
        _uinput._UInputTouchDevice._last_tracking_id = last_tracking_id

    def test_press_other_device_must_not_press_all_of_them(self):
        finger1 = _uinput.Touch(device_class=MultipleUInputTouchBackend)
        finger2 = _uinput.Touch(device_class=MultipleUInputTouchBackend)

        finger1.press(0, 0)
        self.addCleanup(finger1.release)

        self.assertFalse(finger2.pressed)


class DragUInputTouchTestCase(testscenarios.TestWithScenarios, TestCase):

    scenarios = [
        ('drag to top', dict(
            start_x=50, start_y=50, stop_x=50, stop_y=30,
            expected_moves=[call.finger_move(50, 40),
                            call.finger_move(50, 30)])),
        ('drag to bottom', dict(
            start_x=50, start_y=50, stop_x=50, stop_y=70,
            expected_moves=[call.finger_move(50, 60),
                            call.finger_move(50, 70)])),
        ('drag to left', dict(
            start_x=50, start_y=50, stop_x=30, stop_y=50,
            expected_moves=[call.finger_move(40, 50),
                            call.finger_move(30, 50)])),
        ('drag to right', dict(
            start_x=50, start_y=50, stop_x=70, stop_y=50,
            expected_moves=[call.finger_move(60, 50),
                            call.finger_move(70, 50)])),

        ('drag to top-left', dict(
            start_x=50, start_y=50, stop_x=30, stop_y=30,
            expected_moves=[call.finger_move(40, 40),
                            call.finger_move(30, 30)])),
        ('drag to top-right', dict(
            start_x=50, start_y=50, stop_x=70, stop_y=30,
            expected_moves=[call.finger_move(60, 40),
                            call.finger_move(70, 30)])),
        ('drag to bottom-left', dict(
            start_x=50, start_y=50, stop_x=30, stop_y=70,
            expected_moves=[call.finger_move(40, 60),
                            call.finger_move(30, 70)])),
        ('drag to bottom-right', dict(
            start_x=50, start_y=50, stop_x=70, stop_y=70,
            expected_moves=[call.finger_move(60, 60),
                            call.finger_move(70, 70)])),

        ('drag less than rate', dict(
            start_x=50, start_y=50, stop_x=55, stop_y=55,
            expected_moves=[call.finger_move(55, 55)])),

        ('drag with last move less than rate', dict(
            start_x=50, start_y=50, stop_x=65, stop_y=65,
            expected_moves=[call.finger_move(60, 60),
                            call.finger_move(65, 65)])),
    ]

    def setUp(self):
        super(DragUInputTouchTestCase, self).setUp()
        # Mock the sleeps so we don't have to spend time actually sleeping.
        self.addCleanup(utilities.sleep.disable_mock)
        utilities.sleep.enable_mock()

    def get_touch_with_mocked_backend(self):
        touch = _uinput.Touch(device_class=Mock)
        touch._device.mock_add_spec(
            _uinput._UInputTouchDevice, spec_set=True)
        return touch

    def test_drag_moves(self):
        touch = self.get_touch_with_mocked_backend()

        touch.drag(
            self.start_x, self.start_y, self.stop_x, self.stop_y)

        # We don't check the finger down and finger up. They are already
        # tested.
        expected_calls = [ANY] + self.expected_moves + [ANY]
        self.assertEqual(
            expected_calls, touch._device.mock_calls)


class PointerWithTouchBackendTestCase(TestCase):

    def get_pointer_with_touch_backend_with_mock_device(self):
        touch = _uinput.Touch(device_class=Mock)
        touch._device.mock_add_spec(
            _uinput._UInputTouchDevice, spec_set=True)
        pointer = autopilot.input.Pointer(touch)
        return pointer

    def test_drag_with_rate(self):
        pointer = self.get_pointer_with_touch_backend_with_mock_device()
        with patch.object(pointer._device, 'drag') as mock_drag:
            pointer.drag(0, 0, 20, 20, rate='test')

        mock_drag.assert_called_once_with(
            0, 0, 20, 20, rate='test', time_between_events=0.01)

    def test_drag_with_time_between_events(self):
        pointer = self.get_pointer_with_touch_backend_with_mock_device()
        with patch.object(pointer._device, 'drag') as mock_drag:
            pointer.drag(0, 0, 20, 20, time_between_events='test')

        mock_drag.assert_called_once_with(
            0, 0, 20, 20, rate=10, time_between_events='test')

    def test_drag_with_default_parameters(self):
        pointer = self.get_pointer_with_touch_backend_with_mock_device()
        with patch.object(pointer._device, 'drag') as mock_drag:
            pointer.drag(0, 0, 20, 20)

        mock_drag.assert_called_once_with(
            0, 0, 20, 20, rate=10, time_between_events=0.01)