Exemplo n.º 1
0
    def test_battery_linux_kernel(self):
        '''
        Test mocked Linux kernel sysclass for plyer.battery.
        '''
        def false(*args, **kwargs):
            return False

        sysclass = MockedKernelSysclass()

        with patch(target='os.path.exists') as bat_path:
            # first call to trigger exists() call
            platform_import(platform='linux',
                            module_name='battery',
                            whereis_exe=false).instance()
            bat_path.assert_called_once_with(sysclass.path)

            # exists() checked with sysclass path
            # set mock to proceed with this branch
            bat_path.return_value = True

            battery = platform_import(platform='linux',
                                      module_name='battery',
                                      whereis_exe=false).instance()

        stub = Mock(return_value=sysclass.uevent)
        target = 'builtins.open'

        with patch(target=target, new=stub):
            self.assertEqual(
                battery.status, {
                    'isCharging': sysclass.charging == 'Charging',
                    'percentage': sysclass.percentage
                })
Exemplo n.º 2
0
    def test_screenshot_screencapture(self):
        '''
        Test mocked MacOS screencapture for plyer.screenshot.
        '''
        if not PY2:
            print('Can not run until PyOBJus works on Py3.')
            return

        scr = platform_import(platform='macosx',
                              module_name='screenshot',
                              whereis_exe=MockedScreenCapture.whereis_exe)

        # such class exists in screenshot module
        self.assertIn('OSXScreenshot', dir(scr))

        # the required instance is created
        scr = scr.instance()
        self.assertIn('OSXScreenshot', str(scr))

        # move capture from context manager to run without mock
        with patch(target='subprocess.call', new=MockedScreenCapture.call):
            self.assertIsNone(scr.capture())

        scr_path = join(expanduser('~'), 'Pictures', 'screenshot.png')
        self.assertTrue(exists(scr_path))
        remove(scr_path)
Exemplo n.º 3
0
    def test_screenshot_screencapture(self):
        '''
        Test mocked MacOS screencapture for plyer.screenshot.
        '''
        if not PY2:
            print('Can not run until PyOBJus works on Py3.')
            return

        scr = platform_import(
            platform='macosx',
            module_name='screenshot',
            whereis_exe=MockedScreenCapture.whereis_exe
        )

        # such class exists in screenshot module
        self.assertIn('OSXScreenshot', dir(scr))

        # the required instance is created
        scr = scr.instance()
        self.assertIn('OSXScreenshot', str(scr))

        # move capture from context manager to run without mock
        with patch(target='subprocess.call', new=MockedScreenCapture.call):
            self.assertIsNone(scr.capture())

        self.assertTrue(exists(scr.file_path))
        remove(scr.file_path)
Exemplo n.º 4
0
    def test_audio_macosx(self):
        '''
        Test macOS audio start, stop and play

        .. versionadded:: 1.4.0
        '''

        path = join(expanduser('~'), 'Music')
        if not exists(path):
            mkdir(path)

        audio = platform_import(
            platform='macosx',
            module_name='audio',
        )

        self.assertIn('OSXAudio', dir(audio))
        audio = audio.instance()
        self.assertIn('OSXAudio', str(audio))

        self.assertFalse(exists(audio.file_path))
        self.assertIsNone(audio.start())
        time.sleep(0.5)
        self.assertIsNone(audio.stop())
        self.assertIsNone(audio.play())
        time.sleep(0.5)
        self.assertIsNone(audio.stop())

        audio.file_path = audio.file_path.replace(
            'file://', ''
        )

        self.assertTrue(exists(audio.file_path))

        remove(audio.file_path)
Exemplo n.º 5
0
    def test_cpu_win_logical(self):
        cpu = platform_import(platform='win', module_name='cpu')

        cpu = cpu.instance()
        self.assertEqual(
            cpu.logical,
            # https://docs.microsoft.com/en-us/previous-versions/
            # windows/it-pro/windows-xp/bb490954(v=technet.10)
            int(environ['NUMBER_OF_PROCESSORS']))
Exemplo n.º 6
0
 def test_battery_win(self):
     '''
     Test Windows API for plyer.battery.
     '''
     battery = platform_import(platform='win',
                               module_name='battery').instance()
     for key in ('isCharging', 'percentage'):
         self.assertIn(key, battery.status)
         self.assertIsNotNone(battery.status[key])
Exemplo n.º 7
0
    def test_notification_windows(self):
        '''
        Test Windows API for plyer.notification.
        '''
        import ctypes
        from ctypes import (WINFUNCTYPE, POINTER, create_unicode_buffer,
                            c_bool, c_int)
        notif = platform_import(platform='win',
                                module_name='notification').instance()
        enum_windows = ctypes.windll.user32.EnumWindows
        get_class_name = ctypes.windll.user32.GetClassNameW

        # loop over windows and get refs to
        # the opened plyer notifications
        clsnames = []

        def fetch_class(hwnd, *args):
            # pylint: disable=unused-argument
            '''
            EnumWindowsProc callback for EnumWindows.
            '''
            buff = create_unicode_buffer(50)
            get_class_name(hwnd, buff, 50)

            if 'Plyer' in buff.value:
                clsnames.append(buff.value)

        # ensure it's not an empty facade
        self.assertIn('WindowsNotification', str(notif))

        # create enum function for EnumWindows
        enum_windows_proc = WINFUNCTYPE(
            # returns
            c_bool,

            # input params: hwnd, lParam
            POINTER(c_int),
            POINTER(c_int))

        for i in range(3):
            self.show_notification(notif)

            # the balloon needs some time to became visible in WinAPI
            sleep(0.01)

            # fetch window class names
            enum_windows(
                # enum & params
                enum_windows_proc(fetch_class),
                None)

            # 3 active balloons at the same time,
            # class_name is incremented - see WindowsBalloonTip
            self.assertEqual(len(clsnames), i + 1)
            self.assertIn('PlyerTaskbar' + str(i), clsnames)
            clsnames = []
Exemplo n.º 8
0
    def test_battery_linux_kernel(self):
        '''
        Test mocked Linux kernel sysclass for plyer.battery.
        '''

        def false(*args, **kwargs):
            # pylint: disable=unused-argument
            return False

        sysclass = MockedKernelSysclass()

        with patch(target='os.path.exists') as bat_path:
            # first call to trigger exists() call
            platform_import(
                platform='linux',
                module_name='battery',
                whereis_exe=false
            ).instance()
            bat_path.assert_called_once_with(sysclass.path)

            # exists() checked with sysclass path
            # set mock to proceed with this branch
            bat_path.return_value = True

            battery = platform_import(
                platform='linux',
                module_name='battery',
                whereis_exe=false
            ).instance()

        stub = Mock(return_value=sysclass.uevent)
        py2_target = '__builtin__.open'
        py3_target = 'builtins.open'
        target = py3_target if sys.version_info.major == 3 else py2_target

        with patch(target=target, new=stub):
            self.assertEqual(
                battery.status, {
                    'isCharging': sysclass.charging == 'Charging',
                    'percentage': sysclass.percentage
                }
            )
Exemplo n.º 9
0
 def test_battery_win(self):
     '''
     Test Windows API for plyer.battery.
     '''
     battery = platform_import(
         platform='win',
         module_name='battery'
     ).instance()
     for key in ('isCharging', 'percentage'):
         self.assertIn(key, battery.status)
         self.assertIsNotNone(battery.status[key])
Exemplo n.º 10
0
    def test_cpu_linux_physical(self):
        cpu = platform_import(platform='linux',
                              module_name='cpu',
                              whereis_exe=lambda b: b == 'nproc').instance()

        stub = MockedProcinfo
        target = 'builtins.open'

        with patch(target=target, new=stub):
            sb = stub()
            self.assertEqual(cpu.physical, sb.physical)
Exemplo n.º 11
0
    def test_cpu_linux_logical(self):
        '''
        Test mocked Linux NProc for plyer.cpu.
        '''
        cpu = platform_import(platform='linux',
                              module_name='cpu',
                              whereis_exe=MockedNProc.whereis_exe)
        cpu.Popen = MockedNProc
        cpu = cpu.instance()

        self.assertEqual(cpu.logical, MockedNProc.logical())
Exemplo n.º 12
0
    def test_notification_dbus(self):
        '''
        Test mocked Linux DBus for plyer.notification.
        '''
        notif = platform_import(
            platform='linux',
            module_name='notification'
        )
        self.assertIn('NotifyDbus', dir(notif))

        # (3) mocked Interface called from dbus
        interface = Mock()
        interface.side_effect = (interface, )

        # (2) mocked SessionBus called from dbus
        session_bus = Mock()
        session_bus.side_effect = (session_bus, )

        # (1) mocked dbus for import
        dbus = Mock(SessionBus=session_bus, Interface=interface)

        # inject the mocked module
        self.assertNotIn('dbus', sys.modules)
        sys.modules['dbus'] = dbus

        try:
            notif = notif.instance()
            self.assertIn('NotifyDbus', str(notif))

            # call notify()
            self.show_notification(notif)

            # check whether Mocks were called
            dbus.SessionBus.assert_called_once()

            session_bus.get_object.assert_called_once_with(
                'org.freedesktop.Notifications',
                '/org/freedesktop/Notifications'
            )

            interface.Notify.assert_called_once_with(
                TestNotification.data['app_name'],
                0,
                TestNotification.data['app_icon'],
                TestNotification.data['title'],
                TestNotification.data['message'],
                [], [],
                TestNotification.data['timeout'] * 1000
            )
        finally:
            del sys.modules['dbus']
        self.assertNotIn('dbus', sys.modules)
Exemplo n.º 13
0
    def test_devicename_win(self):
        '''
        Test Windows API for plyer.devicename.
        '''
        devicename = platform_import(platform='win', module_name='devicename')
        devicename_instance = devicename.instance()

        with patch.object(socket,
                          'gethostname',
                          return_value='mocked_windows_hostname') as _:

            evaluated_device_name = devicename_instance.device_name
            self.assertEqual(evaluated_device_name, 'mocked_windows_hostname')
Exemplo n.º 14
0
    def test_cpu_win_logical(self):
        cpu = platform_import(
            platform='win',
            module_name='cpu'
        )

        cpu = cpu.instance()
        self.assertEqual(
            cpu.logical,
            # https://docs.microsoft.com/en-us/previous-versions/
            # windows/it-pro/windows-xp/bb490954(v=technet.10)
            int(environ['NUMBER_OF_PROCESSORS'])
        )
Exemplo n.º 15
0
    def test_battery_macosx_instance(self):
        '''
        Test macOS instance for plyer.battery
        '''
        def no_exe(*args, **kwargs):
            return

        battery = platform_import(platform='macosx',
                                  module_name='battery',
                                  whereis_exe=no_exe)

        battery = battery.instance()
        self.assertNotIn('OSXBattery', str(battery))
        self.assertIn('Battery', str(battery))
Exemplo n.º 16
0
    def test_notification_notifysend(self):
        '''
        Test mocked Linux notify-send for plyer.notification.
        '''
        notif = platform_import(platform='linux',
                                module_name='notification',
                                whereis_exe=MockedNotifySend.whereis_exe)
        self.assertIn('NotifySendNotification', dir(notif))
        with patch(target='warnings.warn', new=MockedNotifySend.warn):
            notif = notif.instance()
        self.assertIn('NotifySendNotification', str(notif))

        with patch(target='subprocess.call', new=MockedNotifySend.call):
            self.assertIsNone(self.show_notification(notif))
Exemplo n.º 17
0
    def test_bluetooth_macosx_instance(self):
        '''
        Test macOS instance for plyer.bluetooth.
        '''
        def no_exe(*args, **kwargs):
            return

        bluetooth = platform_import(platform='macosx',
                                    module_name='bluetooth',
                                    whereis_exe=no_exe)

        bluetooth = bluetooth.instance()
        self.assertNotIn('OSXBluetooth', str(bluetooth))
        self.assertIn('Bluetooth', str(bluetooth))
Exemplo n.º 18
0
    def test_cpu_linux_logical(self):
        '''
        Test mocked Linux NProc for plyer.cpu.
        '''
        cpu = platform_import(
            platform='linux',
            module_name='cpu',
            whereis_exe=MockedNProc.whereis_exe
        )
        cpu.Popen = MockedNProc
        cpu = cpu.instance()

        self.assertEqual(
            cpu.logical, MockedNProc.logical()
        )
Exemplo n.º 19
0
    def test_bluetooth_macosx(self):
        '''
        Test macOS system_profiler for plyer.bluetooth.
        '''
        bluetooth = platform_import(
            platform='macosx',
            module_name='bluetooth',
            whereis_exe=MockedSystemProfiler.whereis_exe)

        bluetooth.Popen = MockedSystemProfiler
        self.assertIn('OSXBluetooth', dir(bluetooth))
        bluetooth = bluetooth.instance()
        self.assertIn('OSXBluetooth', str(bluetooth))

        self.assertEqual(bluetooth.info, MockedSystemProfiler.get_info())
Exemplo n.º 20
0
    def test_battery_linux_upower(self):
        '''
        Test mocked Linux UPower for plyer.battery.
        '''
        battery = platform_import(platform='linux',
                                  module_name='battery',
                                  whereis_exe=MockedUPower.whereis_exe)
        battery.Popen = MockedUPower
        battery = battery.instance()

        self.assertEqual(
            battery.status, {
                'isCharging': MockedUPower.charging(),
                'percentage': MockedUPower.percentage()
            })
Exemplo n.º 21
0
    def test_notification_notifysend(self):
        '''
        Test mocked Linux notify-send for plyer.notification.
        '''
        notif = platform_import(
            platform='linux',
            module_name='notification',
            whereis_exe=MockedNotifySend.whereis_exe
        )
        self.assertIn('NotifySendNotification', dir(notif))
        with patch(target='warnings.warn', new=MockedNotifySend.warn):
            notif = notif.instance()
        self.assertIn('NotifySendNotification', str(notif))

        with patch(target='subprocess.call', new=MockedNotifySend.call):
            self.assertIsNone(self.show_notification(notif))
Exemplo n.º 22
0
    def test_uniqueid_win(self):
        '''
        Test Windows API for plyer.uniqueid.
        '''
        try:
            from winreg import (  # pylint: disable=import-error
                HKEY_LOCAL_MACHINE as HKLM,
                KEY_READ as READ, KEY_WOW64_64KEY as VIEW
            )
        except ImportError:
            from _winreg import (  # pylint: disable=import-error
                HKEY_LOCAL_MACHINE as HKLM,
                KEY_READ as READ, KEY_WOW64_64KEY as VIEW
            )

        # mock the 'regedit' alias for winreg,
        # see if the import passes and get the instance
        regedit_mod = 'plyer.platforms.win.uniqueid.regedit'
        with patch(target=regedit_mod):
            uniqueid_ = platform_import(
                platform='win',
                module_name='uniqueid'
            )
            uniqueid = uniqueid_.instance()
            self.assertIsInstance(uniqueid_.regedit, Mock)

        # out of mocking block, regedit should be a winreg module
        self.assertIsInstance(uniqueid_.regedit, type(unittest))

        # OpenKey is supposed to return a handle to registry key
        regedit_opkey = 'plyer.platforms.win.uniqueid.regedit.OpenKey'
        with patch(target=regedit_opkey, return_value='unicorn') as opkey:

            # QueryValueEx is supposed to return 2 packed values
            # (key, type_id)
            queryval = 'plyer.platforms.win.uniqueid.regedit.QueryValueEx'
            retval = ('unique', None)
            with patch(target=queryval, return_value=retval) as query:
                uid = uniqueid.id
                opkey.assert_called_once_with(
                    # key, subkey
                    HKLM, r'SOFTWARE\\Microsoft\\Cryptography',
                    # reserved integer (has to be 0 - zero), access mask
                    0, READ | VIEW
                )
                query.assert_called_once_with('unicorn', 'MachineGuid')
                self.assertEqual(uid, retval[0])
Exemplo n.º 23
0
    def test_battery_macosx_instance(self):
        '''
        Test macOS instance for plyer.battery
        '''

        def no_exe(*args, **kwargs):
            return

        battery = platform_import(
            platform='macosx',
            module_name='battery',
            whereis_exe=no_exe
        )

        battery = battery.instance()
        self.assertNotIn('OSXBattery', str(battery))
        self.assertIn('Battery', str(battery))
Exemplo n.º 24
0
    def test_bluetooth_macosx_instance(self):
        '''
        Test macOS instance for plyer.bluetooth.
        '''

        def no_exe(*args, **kwargs):
            return

        bluetooth = platform_import(
            platform='macosx',
            module_name='bluetooth',
            whereis_exe=no_exe
        )

        bluetooth = bluetooth.instance()
        self.assertNotIn('OSXBluetooth', str(bluetooth))
        self.assertIn('Bluetooth', str(bluetooth))
Exemplo n.º 25
0
    def test_cpu_linux_cache(self):
        cpu = platform_import(platform='linux',
                              module_name='cpu',
                              whereis_exe=lambda b: b == 'nproc').instance()

        stub = MockedKernelCPU
        target = 'builtins.open'
        sub_target = 'plyer.platforms.linux.cpu.listdir'

        with patch(target=target, new=stub):
            with patch(target=sub_target, return_value=stub().listdir):
                sb = stub()
                self.assertEqual(cpu.cache, {
                    'L1': sb.cores * 2,
                    'L2': sb.cores,
                    'L3': sb.cores
                })
Exemplo n.º 26
0
    def test_cpu_linux_physical(self):
        cpu = platform_import(
            platform='linux',
            module_name='cpu',
            whereis_exe=lambda b: b == 'nproc'
        ).instance()

        stub = MockedProcinfo
        py2_target = '__builtin__.open'
        py3_target = 'builtins.open'
        target = py3_target if sys.version_info.major == 3 else py2_target

        with patch(target=target, new=stub):
            sb = stub()
            self.assertEqual(
                cpu.physical, sb.physical
            )
Exemplo n.º 27
0
    def test_email_win():
        '''
        Test starting Windows email client for plyer.email.
        '''
        email = platform_import(platform='win', module_name='email')

        try:
            test_mailto = 'mailto:recipient?subject=subject&body=text'
            with patch(target='os.startfile', new=Mock()) as startfile:
                email.instance().send(recipient='recipient',
                                      subject='subject',
                                      text='text')
            startfile.assert_called_once_with(test_mailto)
        except WindowsError:  # pylint: disable=undefined-variable
            # if WE is raised, email client isn't found,
            # but the platform code works correctly
            print('Mail client not found!')
Exemplo n.º 28
0
    def test_battery_macosx(self):
        '''
        Test macOS IOReg for plyer.battery.
        '''
        battery = platform_import(platform='macosx',
                                  module_name='battery',
                                  whereis_exe=MockedIOReg.whereis_exe)

        battery.Popen = MockedIOReg
        self.assertIn('OSXBattery', dir(battery))
        battery = battery.instance()
        self.assertIn('OSXBattery', str(battery))

        self.assertEqual(
            battery.status, {
                'isCharging': MockedIOReg.charging(),
                'percentage': MockedIOReg.percentage()
            })
Exemplo n.º 29
0
    def test_bluetooth_macosx(self):
        '''
        Test macOS system_profiler for plyer.bluetooth.
        '''
        bluetooth = platform_import(
            platform='macosx',
            module_name='bluetooth',
            whereis_exe=MockedSystemProfiler.whereis_exe
        )

        bluetooth.Popen = MockedSystemProfiler
        self.assertIn('OSXBluetooth', dir(bluetooth))
        bluetooth = bluetooth.instance()
        self.assertIn('OSXBluetooth', str(bluetooth))

        self.assertEqual(
            bluetooth.info, MockedSystemProfiler.get_info()
        )
Exemplo n.º 30
0
    def test_battery_linux_upower(self):
        '''
        Test mocked Linux UPower for plyer.battery.
        '''
        battery = platform_import(
            platform='linux',
            module_name='battery',
            whereis_exe=MockedUPower.whereis_exe
        )
        battery.Popen = MockedUPower
        battery = battery.instance()

        self.assertEqual(
            battery.status, {
                'isCharging': MockedUPower.charging(),
                'percentage': MockedUPower.percentage()
            }
        )
Exemplo n.º 31
0
    def test_uniqueid_win(self):
        '''
        Test Windows API for plyer.uniqueid.
        '''
        try:
            from winreg import (  # pylint: disable=import-error
                HKEY_LOCAL_MACHINE as HKLM, KEY_READ as READ, KEY_WOW64_64KEY
                as VIEW)
        except ImportError:
            from _winreg import (  # pylint: disable=import-error
                HKEY_LOCAL_MACHINE as HKLM, KEY_READ as READ, KEY_WOW64_64KEY
                as VIEW)

        # mock the 'regedit' alias for winreg,
        # see if the import passes and get the instance
        regedit_mod = 'plyer.platforms.win.uniqueid.regedit'
        with patch(target=regedit_mod):
            uniqueid_ = platform_import(platform='win', module_name='uniqueid')
            uniqueid = uniqueid_.instance()
            self.assertIsInstance(uniqueid_.regedit, Mock)

        # out of mocking block, regedit should be a winreg module
        self.assertIsInstance(uniqueid_.regedit, type(unittest))

        # OpenKey is supposed to return a handle to registry key
        regedit_opkey = 'plyer.platforms.win.uniqueid.regedit.OpenKey'
        with patch(target=regedit_opkey, return_value='unicorn') as opkey:

            # QueryValueEx is supposed to return 2 packed values
            # (key, type_id)
            queryval = 'plyer.platforms.win.uniqueid.regedit.QueryValueEx'
            retval = ('unique', None)
            with patch(target=queryval, return_value=retval) as query:
                uid = uniqueid.id
                opkey.assert_called_once_with(
                    # key, subkey
                    HKLM,
                    r'SOFTWARE\\Microsoft\\Cryptography',
                    # reserved integer (has to be 0 - zero), access mask
                    0,
                    READ | VIEW)
                query.assert_called_once_with('unicorn', 'MachineGuid')
                self.assertEqual(uid, retval[0])
Exemplo n.º 32
0
    def test_audio_win(self):
        '''
        Test Windows audio start, stop and play

        .. versionadded:: 1.4.0
        '''

        if environ.get('APPVEYOR'):
            # Appveyor has no recording device installed
            # therefore the test will 100% fail
            #
            # error_code: 328
            # message:
            # 'No wave device is installed that can record files in the current
            # format. To install a wave device, go to Control Panel, click P')
            return

        path = join(environ['USERPROFILE'], 'Music')
        if not exists(path):
            mkdir(path)

        audio = platform_import(
            platform='win',
            module_name='audio',
        )

        self.assertIn('WinAudio', dir(audio))
        audio = audio.instance()
        self.assertIn('WinAudio', str(audio))

        self.assertFalse(exists(audio.file_path))
        self.assertIsNone(audio.start())
        time.sleep(0.5)
        self.assertIsNone(audio.stop())
        self.assertIsNone(audio.play())
        time.sleep(0.5)
        self.assertIsNone(audio.stop())

        self.assertTrue(exists(audio.file_path))

        remove(audio.file_path)
Exemplo n.º 33
0
    def test_storagepath_windows(self):
        '''
        Test win for plyer.storagepath.
        '''
        storagepath = platform_import(platform='win',
                                      module_name='storagepath')

        self.assertIn('WinStoragePath', dir(storagepath))
        storagepath = storagepath.instance()
        self.assertIn('WinStoragePath', str(storagepath))

        path_format = ':\\'

        self.assertIn(path_format, storagepath.get_home_dir())
        self.assertIn(path_format, storagepath.get_root_dir())
        self.assertIn(path_format, storagepath.get_documents_dir())
        self.assertIn(path_format, storagepath.get_downloads_dir())
        self.assertIn(path_format, storagepath.get_videos_dir())
        self.assertIn(path_format, storagepath.get_music_dir())
        self.assertIn(path_format, storagepath.get_pictures_dir())
        self.assertIn(path_format, storagepath.get_application_dir())
Exemplo n.º 34
0
    def test_storagepath_macosx(self):
        '''
        Test macOS for plyer.storagepath.
        '''
        storagepath = platform_import(platform='macosx',
                                      module_name='storagepath')

        self.assertIn('OSXStoragePath', dir(storagepath))
        storagepath = storagepath.instance()
        self.assertIn('OSXStoragePath', str(storagepath))

        path_format = 'file:///Users/'

        self.assertIn(path_format, storagepath.get_home_dir())
        self.assertIn('/', storagepath.get_root_dir())
        self.assertIn(path_format, storagepath.get_documents_dir())
        self.assertIn(path_format, storagepath.get_downloads_dir())
        self.assertIn(path_format, storagepath.get_videos_dir())
        self.assertIn(path_format, storagepath.get_music_dir())
        self.assertIn(path_format, storagepath.get_pictures_dir())
        self.assertIn(path_format, storagepath.get_application_dir())
Exemplo n.º 35
0
    def test_battery_macosx(self):
        '''
        Test macOS IOReg for plyer.battery.
        '''
        battery = platform_import(
            platform='macosx',
            module_name='battery',
            whereis_exe=MockedIOReg.whereis_exe
        )

        battery.Popen = MockedIOReg
        self.assertIn('OSXBattery', dir(battery))
        battery = battery.instance()
        self.assertIn('OSXBattery', str(battery))

        self.assertEqual(
            battery.status, {
                'isCharging': MockedIOReg.charging(),
                'percentage': MockedIOReg.percentage()
            }
        )
Exemplo n.º 36
0
    def test_email_win():
        '''
        Test starting Windows email client for plyer.email.
        '''
        email = platform_import(
            platform='win',
            module_name='email'
        )

        try:
            test_mailto = 'mailto:recipient?subject=subject&body=text'
            with patch(target='os.startfile', new=Mock()) as startfile:
                email.instance().send(
                    recipient='recipient',
                    subject='subject',
                    text='text'
                )
            startfile.assert_called_once_with(test_mailto)
        except WindowsError:  # pylint: disable=undefined-variable
            # if WE is raised, email client isn't found,
            # but the platform code works correctly
            print('Mail client not found!')
Exemplo n.º 37
0
    def test_cpu_linux_cache(self):
        cpu = platform_import(
            platform='linux',
            module_name='cpu',
            whereis_exe=lambda b: b == 'nproc'
        ).instance()

        stub = MockedKernelCPU
        py2_target = '__builtin__.open'
        py3_target = 'builtins.open'
        target = py3_target if sys.version_info.major == 3 else py2_target
        sub_target = 'plyer.platforms.linux.cpu.listdir'

        with patch(target=target, new=stub):
            with patch(target=sub_target, return_value=stub().listdir):
                sb = stub()
                self.assertEqual(
                    cpu.cache, {
                        'L1': sb.cores * 2,
                        'L2': sb.cores,
                        'L3': sb.cores
                    }
                )
Exemplo n.º 38
0
    def test_storagepath_macosx(self):
        '''
        Test macOS for plyer.storagepath.
        '''
        storagepath = platform_import(
            platform='macosx',
            module_name='storagepath'
        )

        self.assertIn('OSXStoragePath', dir(storagepath))
        storagepath = storagepath.instance()
        self.assertIn('OSXStoragePath', str(storagepath))

        path_format = 'file:///Users/'

        self.assertIn(path_format, storagepath.get_home_dir())
        self.assertIn('/', storagepath.get_root_dir())
        self.assertIn(path_format, storagepath.get_documents_dir())
        self.assertIn(path_format, storagepath.get_downloads_dir())
        self.assertIn(path_format, storagepath.get_videos_dir())
        self.assertIn(path_format, storagepath.get_music_dir())
        self.assertIn(path_format, storagepath.get_pictures_dir())
        self.assertIn(path_format, storagepath.get_application_dir())
Exemplo n.º 39
0
    def test_screenshot_xwd(self):
        '''
        Test mocked X11 xwd for plyer.screenshot.
        '''
        scr = platform_import(
            platform='linux',
            module_name='screenshot',
            whereis_exe=MockedXWD.whereis_exe
        )

        # such class exists in screenshot module
        self.assertIn('LinuxScreenshot', dir(scr))

        # the required instance is created
        scr = scr.instance()
        self.assertIn('LinuxScreenshot', str(scr))

        # move capture from context manager to run without mock
        with patch(target='subprocess.call', new=MockedXWD.call):
            self.assertIsNone(scr.capture())

        self.assertTrue(exists(scr.file_path))
        remove(scr.file_path)
Exemplo n.º 40
0
    def test_screenshot_screencapture(self):
        '''
        Test mocked MacOS screencapture for plyer.screenshot.
        '''
        scr = platform_import(
            platform='macosx',
            module_name='screenshot',
            whereis_exe=MockedScreenCapture.whereis_exe
        )

        # such class exists in screenshot module
        self.assertIn('OSXScreenshot', dir(scr))

        # the required instance is created
        scr = scr.instance()
        self.assertIn('OSXScreenshot', str(scr))

        # move capture from context manager to run without mock
        with patch(target='subprocess.call', new=MockedScreenCapture.call):
            self.assertIsNone(scr.capture())

        self.assertTrue(exists(scr.file_path))
        remove(scr.file_path)
Exemplo n.º 41
0
    def test_notification_windows(self):
        '''
        Test Windows API for plyer.notification.
        '''
        import ctypes
        from ctypes import (
            WINFUNCTYPE, POINTER,
            create_unicode_buffer,
            c_bool, c_int
        )
        notif = platform_import(
            platform='win',
            module_name='notification'
        ).instance()
        enum_windows = ctypes.windll.user32.EnumWindows
        get_class_name = ctypes.windll.user32.GetClassNameW

        # loop over windows and get refs to
        # the opened plyer notifications
        clsnames = []

        def fetch_class(hwnd, *args):
            # pylint: disable=unused-argument
            '''
            EnumWindowsProc callback for EnumWindows.
            '''
            buff = create_unicode_buffer(50)
            get_class_name(hwnd, buff, 50)

            if 'Plyer' in buff.value:
                clsnames.append(buff.value)

        # ensure it's not an empty facade
        self.assertIn('WindowsNotification', str(notif))

        # create enum function for EnumWindows
        enum_windows_proc = WINFUNCTYPE(
            # returns
            c_bool,

            # input params: hwnd, lParam
            POINTER(c_int), POINTER(c_int)
        )

        for i in range(3):
            self.show_notification(notif)

            # the balloon needs some time to became visible in WinAPI
            sleep(0.2)

            # fetch window class names
            enum_windows(
                # enum & params
                enum_windows_proc(fetch_class), None
            )

            # 3 active balloons at the same time,
            # class_name is incremented - see WindowsBalloonTip
            self.assertEqual(len(clsnames), i + 1)
            self.assertIn('PlyerTaskbar' + str(i), clsnames)
            clsnames = []