def test_get_kernel_version(self):
     if not POSIX:
         self.assertEqual(get_kernel_version(), tuple())
     else:
         kernel = get_kernel_version()
         assert kernel, kernel
         self.assertIn('.'.join(map(str, kernel)), sh("uname -a"))
Ejemplo n.º 2
0
 def test_get_kernel_version(self):
     if not POSIX:
         self.assertEqual(get_kernel_version(), tuple())
     else:
         kernel = get_kernel_version()
         assert kernel, kernel
         self.assertIn('.'.join(map(str, kernel)), sh("uname -a"))
Ejemplo n.º 3
0
    def test_num_fds(self):
        # Note: this fails from time to time; I'm keen on thinking
        # it doesn't mean something is broken
        def call(p, attr):
            args = ()
            attr = getattr(p, name, None)
            if attr is not None and callable(attr):
                if name == 'rlimit':
                    args = (psutil.RLIMIT_NOFILE, )
                attr(*args)
            else:
                attr

        p = psutil.Process(os.getpid())
        failures = []
        ignored_names = [
            'terminate', 'kill', 'suspend', 'resume', 'nice', 'send_signal',
            'wait', 'children', 'as_dict', 'memory_info_ex', 'parent',
            'parents'
        ]
        if LINUX and get_kernel_version() < (2, 6, 36):
            ignored_names.append('rlimit')
        if LINUX and get_kernel_version() < (2, 6, 23):
            ignored_names.append('num_ctx_switches')
        for name in dir(psutil.Process):
            if (name.startswith('_') or name in ignored_names):
                continue
            else:
                try:
                    num1 = p.num_fds()
                    for x in range(2):
                        call(p, name)
                    num2 = p.num_fds()
                except psutil.AccessDenied:
                    pass
                else:
                    if abs(num2 - num1) > 1:
                        fail = "failure while processing Process.%s method " \
                               "(before=%s, after=%s)" % (name, num1, num2)
                        failures.append(fail)
        if failures:
            self.fail('\n' + '\n'.join(failures))
Ejemplo n.º 4
0
    def test_num_fds(self):
        # Note: this fails from time to time; I'm keen on thinking
        # it doesn't mean something is broken
        def call(p, attr):
            args = ()
            attr = getattr(p, name, None)
            if attr is not None and callable(attr):
                if name == 'rlimit':
                    args = (psutil.RLIMIT_NOFILE,)
                attr(*args)
            else:
                attr

        p = psutil.Process(os.getpid())
        failures = []
        ignored_names = ['terminate', 'kill', 'suspend', 'resume', 'nice',
                         'send_signal', 'wait', 'children', 'as_dict',
                         'memory_info_ex']
        if LINUX and get_kernel_version() < (2, 6, 36):
            ignored_names.append('rlimit')
        if LINUX and get_kernel_version() < (2, 6, 23):
            ignored_names.append('num_ctx_switches')
        for name in dir(psutil.Process):
            if (name.startswith('_') or name in ignored_names):
                continue
            else:
                try:
                    num1 = p.num_fds()
                    for x in range(2):
                        call(p, name)
                    num2 = p.num_fds()
                except psutil.AccessDenied:
                    pass
                else:
                    if abs(num2 - num1) > 1:
                        fail = "failure while processing Process.%s method " \
                               "(before=%s, after=%s)" % (name, num1, num2)
                        failures.append(fail)
        if failures:
            self.fail('\n' + '\n'.join(failures))
Ejemplo n.º 5
0
    def test_linux_rlimit(self):
        ae = self.assertEqual
        hasit = LINUX and get_kernel_version() >= (2, 6, 36)
        ae(hasattr(psutil.Process, "rlimit"), hasit)
        ae(hasattr(psutil, "RLIM_INFINITY"), hasit)
        ae(hasattr(psutil, "RLIMIT_AS"), hasit)
        ae(hasattr(psutil, "RLIMIT_CORE"), hasit)
        ae(hasattr(psutil, "RLIMIT_CPU"), hasit)
        ae(hasattr(psutil, "RLIMIT_DATA"), hasit)
        ae(hasattr(psutil, "RLIMIT_FSIZE"), hasit)
        ae(hasattr(psutil, "RLIMIT_LOCKS"), hasit)
        ae(hasattr(psutil, "RLIMIT_MEMLOCK"), hasit)
        ae(hasattr(psutil, "RLIMIT_NOFILE"), hasit)
        ae(hasattr(psutil, "RLIMIT_NPROC"), hasit)
        ae(hasattr(psutil, "RLIMIT_RSS"), hasit)
        ae(hasattr(psutil, "RLIMIT_STACK"), hasit)

        hasit = LINUX and get_kernel_version() >= (3, 0)
        ae(hasattr(psutil, "RLIMIT_MSGQUEUE"), hasit)
        ae(hasattr(psutil, "RLIMIT_NICE"), hasit)
        ae(hasattr(psutil, "RLIMIT_RTPRIO"), hasit)
        ae(hasattr(psutil, "RLIMIT_RTTIME"), hasit)
        ae(hasattr(psutil, "RLIMIT_SIGPENDING"), hasit)
Ejemplo n.º 6
0
    def test_linux_rlimit(self):
        ae = self.assertEqual
        hasit = LINUX and get_kernel_version() >= (2, 6, 36)
        ae(hasattr(psutil.Process, "rlimit"), hasit)
        ae(hasattr(psutil, "RLIM_INFINITY"), hasit)
        ae(hasattr(psutil, "RLIMIT_AS"), hasit)
        ae(hasattr(psutil, "RLIMIT_CORE"), hasit)
        ae(hasattr(psutil, "RLIMIT_CPU"), hasit)
        ae(hasattr(psutil, "RLIMIT_DATA"), hasit)
        ae(hasattr(psutil, "RLIMIT_FSIZE"), hasit)
        ae(hasattr(psutil, "RLIMIT_LOCKS"), hasit)
        ae(hasattr(psutil, "RLIMIT_MEMLOCK"), hasit)
        ae(hasattr(psutil, "RLIMIT_NOFILE"), hasit)
        ae(hasattr(psutil, "RLIMIT_NPROC"), hasit)
        ae(hasattr(psutil, "RLIMIT_RSS"), hasit)
        ae(hasattr(psutil, "RLIMIT_STACK"), hasit)

        hasit = LINUX and get_kernel_version() >= (3, 0)
        ae(hasattr(psutil, "RLIMIT_MSGQUEUE"), hasit)
        ae(hasattr(psutil, "RLIMIT_NICE"), hasit)
        ae(hasattr(psutil, "RLIMIT_RTPRIO"), hasit)
        ae(hasattr(psutil, "RLIMIT_RTTIME"), hasit)
        ae(hasattr(psutil, "RLIMIT_SIGPENDING"), hasit)
Ejemplo n.º 7
0
class TestMisc(unittest.TestCase):
    @mock.patch('psutil.traceback.print_exc')
    def test_no_procfs_on_import(self, tb):
        my_procfs = tempfile.mkdtemp()

        with open(os.path.join(my_procfs, 'stat'), 'w') as f:
            f.write('cpu   0 0 0 0 0 0 0 0 0 0\n')
            f.write('cpu0  0 0 0 0 0 0 0 0 0 0\n')
            f.write('cpu1  0 0 0 0 0 0 0 0 0 0\n')

        try:
            orig_open = open

            def open_mock(name, *args, **kwargs):
                if name.startswith('/proc'):
                    raise IOError(errno.ENOENT, 'rejecting access for test')
                return orig_open(name, *args, **kwargs)

            patch_point = 'builtins.open' if PY3 else '__builtin__.open'
            with mock.patch(patch_point, side_effect=open_mock):
                importlib.reload(psutil)
                assert tb.called

                self.assertRaises(IOError, psutil.cpu_times)
                self.assertRaises(IOError, psutil.cpu_times, percpu=True)
                self.assertRaises(IOError, psutil.cpu_percent)
                self.assertRaises(IOError, psutil.cpu_percent, percpu=True)
                self.assertRaises(IOError, psutil.cpu_times_percent)
                self.assertRaises(IOError,
                                  psutil.cpu_times_percent,
                                  percpu=True)

                psutil.PROCFS_PATH = my_procfs

                self.assertEqual(psutil.cpu_percent(), 0)
                self.assertEqual(sum(psutil.cpu_times_percent()), 0)

                # since we don't know the number of CPUs at import time,
                # we awkwardly say there are none until the second call
                per_cpu_percent = psutil.cpu_percent(percpu=True)
                self.assertEqual(sum(per_cpu_percent), 0)

                # ditto awkward length
                per_cpu_times_percent = psutil.cpu_times_percent(percpu=True)
                self.assertEqual(sum(map(sum, per_cpu_times_percent)), 0)

                # much user, very busy
                with open(os.path.join(my_procfs, 'stat'), 'w') as f:
                    f.write('cpu   1 0 0 0 0 0 0 0 0 0\n')
                    f.write('cpu0  1 0 0 0 0 0 0 0 0 0\n')
                    f.write('cpu1  1 0 0 0 0 0 0 0 0 0\n')

                self.assertNotEqual(psutil.cpu_percent(), 0)
                self.assertNotEqual(sum(psutil.cpu_percent(percpu=True)), 0)
                self.assertNotEqual(sum(psutil.cpu_times_percent()), 0)
                self.assertNotEqual(
                    sum(map(sum, psutil.cpu_times_percent(percpu=True))), 0)
        finally:
            shutil.rmtree(my_procfs)
            importlib.reload(psutil)

        self.assertEqual(psutil.PROCFS_PATH, '/proc')

    @unittest.skipUnless(get_kernel_version() >= (2, 6, 36),
                         "prlimit() not available on this Linux kernel version"
                         )
    def test_prlimit_availability(self):
        # prlimit() should be available starting from kernel 2.6.36
        p = psutil.Process(os.getpid())
        p.rlimit(psutil.RLIMIT_NOFILE)
        # if prlimit() is supported *at least* these constants should
        # be available
        self.assertTrue(hasattr(psutil, "RLIM_INFINITY"))
        self.assertTrue(hasattr(psutil, "RLIMIT_AS"))
        self.assertTrue(hasattr(psutil, "RLIMIT_CORE"))
        self.assertTrue(hasattr(psutil, "RLIMIT_CPU"))
        self.assertTrue(hasattr(psutil, "RLIMIT_DATA"))
        self.assertTrue(hasattr(psutil, "RLIMIT_FSIZE"))
        self.assertTrue(hasattr(psutil, "RLIMIT_LOCKS"))
        self.assertTrue(hasattr(psutil, "RLIMIT_MEMLOCK"))
        self.assertTrue(hasattr(psutil, "RLIMIT_NOFILE"))
        self.assertTrue(hasattr(psutil, "RLIMIT_NPROC"))
        self.assertTrue(hasattr(psutil, "RLIMIT_RSS"))
        self.assertTrue(hasattr(psutil, "RLIMIT_STACK"))

    @unittest.skipUnless(
        get_kernel_version() >= (3, 0),
        "prlimit constants not available on this Linux kernel version")
    def test_resource_consts_kernel_v(self):
        # more recent constants
        self.assertTrue(hasattr(psutil, "RLIMIT_MSGQUEUE"))
        self.assertTrue(hasattr(psutil, "RLIMIT_NICE"))
        self.assertTrue(hasattr(psutil, "RLIMIT_RTPRIO"))
        self.assertTrue(hasattr(psutil, "RLIMIT_RTTIME"))
        self.assertTrue(hasattr(psutil, "RLIMIT_SIGPENDING"))

    def test_boot_time_mocked(self):
        with mock.patch('psutil._pslinux.open', create=True) as m:
            self.assertRaises(RuntimeError, psutil._pslinux.boot_time)
            assert m.called

    def test_users_mocked(self):
        # Make sure ':0' and ':0.0' (returned by C ext) are converted
        # to 'localhost'.
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', ':0',
                                       1436573184.0, True)]) as m:
            self.assertEqual(psutil.users()[0].host, 'localhost')
            assert m.called
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', ':0.0',
                                       1436573184.0, True)]) as m:
            self.assertEqual(psutil.users()[0].host, 'localhost')
            assert m.called
        # ...otherwise it should be returned as-is
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', 'foo',
                                       1436573184.0, True)]) as m:
            self.assertEqual(psutil.users()[0].host, 'foo')
            assert m.called

    def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir)

    def test_sector_size_mock(self):
        # Test SECTOR_SIZE fallback in case 'hw_sector_size' file
        # does not exist.
        def open_mock(name, *args, **kwargs):
            if PY3 and isinstance(name, bytes):
                name = name.decode()
            if name.startswith("/sys/block/sda/queue/hw_sector_size"):
                flag.append(None)
                raise IOError(errno.ENOENT, '')
            else:
                return orig_open(name, *args, **kwargs)

        flag = []
        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        try:
            with mock.patch(patch_point, side_effect=open_mock):
                importlib.reload(psutil._pslinux)
                importlib.reload(psutil)
                self.assertEqual(flag, [None])
                self.assertEqual(psutil._pslinux.SECTOR_SIZE, 512)
        finally:
            importlib.reload(psutil._pslinux)
            importlib.reload(psutil)