当前位置: 首页>>代码示例>>Python>>正文


Python mock.patch函数代码示例

本文整理汇总了Python中psutil.tests.mock.patch函数的典型用法代码示例。如果您正苦于以下问题:Python patch函数的具体用法?Python patch怎么用?Python patch使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了patch函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_win_service_get

    def test_win_service_get(self):
        name = next(psutil.win_service_iter()).name()

        with self.assertRaises(psutil.NoSuchProcess) as cm:
            psutil.win_service_get(name + '???')
        self.assertEqual(cm.exception.name, name + '???')

        # test NoSuchProcess
        service = psutil.win_service_get(name)
        exc = WindowsError(
            psutil._psplatform.cext.ERROR_SERVICE_DOES_NOT_EXIST, "")
        with mock.patch("psutil._psplatform.cext.winservice_query_status",
                        side_effect=exc):
            self.assertRaises(psutil.NoSuchProcess, service.status)
        with mock.patch("psutil._psplatform.cext.winservice_query_config",
                        side_effect=exc):
            self.assertRaises(psutil.NoSuchProcess, service.username)

        # test AccessDenied
        exc = WindowsError(
            psutil._psplatform.cext.ERROR_ACCESS_DENIED, "")
        with mock.patch("psutil._psplatform.cext.winservice_query_status",
                        side_effect=exc):
            self.assertRaises(psutil.AccessDenied, service.status)
        with mock.patch("psutil._psplatform.cext.winservice_query_config",
                        side_effect=exc):
            self.assertRaises(psutil.AccessDenied, service.username)

        # test __str__ and __repr__
        self.assertIn(service.name(), str(service))
        self.assertIn(service.display_name(), str(service))
        self.assertIn(service.name(), repr(service))
        self.assertIn(service.display_name(), repr(service))
开发者ID:4sp1r3,项目名称:psutil,代码行数:33,代码来源:test_windows.py

示例2: test_supports_ipv6

    def test_supports_ipv6(self):
        self.addCleanup(supports_ipv6.cache_clear)
        if supports_ipv6():
            with mock.patch('psutil._common.socket') as s:
                s.has_ipv6 = False
                supports_ipv6.cache_clear()
                assert not supports_ipv6()

            supports_ipv6.cache_clear()
            with mock.patch('psutil._common.socket.socket',
                            side_effect=socket.error) as s:
                assert not supports_ipv6()
                assert s.called

            supports_ipv6.cache_clear()
            with mock.patch('psutil._common.socket.socket',
                            side_effect=socket.gaierror) as s:
                assert not supports_ipv6()
                supports_ipv6.cache_clear()
                assert s.called

            supports_ipv6.cache_clear()
            with mock.patch('psutil._common.socket.socket.bind',
                            side_effect=socket.gaierror) as s:
                assert not supports_ipv6()
                supports_ipv6.cache_clear()
                assert s.called
        else:
            with self.assertRaises(Exception):
                sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
                sock.bind(("::1", 0))
开发者ID:jomann09,项目名称:psutil,代码行数:31,代码来源:test_misc.py

示例3: test_threads_mocked

    def test_threads_mocked(self):
        # Test the case where os.listdir() returns a file (thread)
        # which no longer exists by the time we open() it (race
        # condition). threads() is supposed to ignore that instead
        # of raising NSP.
        def open_mock(name, *args, **kwargs):
            if name.startswith('/proc/%s/task' % os.getpid()):
                raise IOError(errno.ENOENT, "")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            ret = psutil.Process().threads()
            assert m.called
            self.assertEqual(ret, [])

        # ...but if it bumps into something != ENOENT we want an
        # exception.
        def open_mock(name, *args, **kwargs):
            if name.startswith('/proc/%s/task' % os.getpid()):
                raise IOError(errno.EPERM, "")
            else:
                return orig_open(name, *args, **kwargs)

        with mock.patch(patch_point, side_effect=open_mock):
            self.assertRaises(psutil.AccessDenied, psutil.Process().threads)
开发者ID:4sp1r3,项目名称:psutil,代码行数:28,代码来源:test_linux.py

示例4: test_boot_time_fluctuation

 def test_boot_time_fluctuation(self):
     # https://github.com/giampaolo/psutil/issues/1007
     with mock.patch('psutil._pswindows.cext.boot_time', return_value=5):
         self.assertEqual(psutil.boot_time(), 5)
     with mock.patch('psutil._pswindows.cext.boot_time', return_value=4):
         self.assertEqual(psutil.boot_time(), 5)
     with mock.patch('psutil._pswindows.cext.boot_time', return_value=6):
         self.assertEqual(psutil.boot_time(), 5)
     with mock.patch('psutil._pswindows.cext.boot_time', return_value=333):
         self.assertEqual(psutil.boot_time(), 333)
开发者ID:Colorado4Wheeler,项目名称:Mac-Commander,代码行数:10,代码来源:test_windows.py

示例5: test_name_long_cmdline_nsp_exc

 def test_name_long_cmdline_nsp_exc(self):
     # Same as above but emulates a case where cmdline() raises NSP
     # which is supposed to propagate.
     name = "long-program-name"
     with mock.patch("psutil._psplatform.Process.name",
                     return_value=name):
         with mock.patch("psutil._psplatform.Process.cmdline",
                         side_effect=psutil.NoSuchProcess(0, "")):
             p = psutil.Process()
             self.assertRaises(psutil.NoSuchProcess, p.name)
开发者ID:jomann09,项目名称:psutil,代码行数:10,代码来源:test_posix.py

示例6: test_name_long_cmdline_ad_exc

 def test_name_long_cmdline_ad_exc(self):
     # Same as above but emulates a case where cmdline() raises
     # AccessDenied in which case psutil is supposed to return
     # the truncated name instead of crashing.
     name = "long-program-name"
     with mock.patch("psutil._psplatform.Process.name",
                     return_value=name):
         with mock.patch("psutil._psplatform.Process.cmdline",
                         side_effect=psutil.AccessDenied(0, "")):
             p = psutil.Process()
             self.assertEqual(p.name(), "long-program-name")
开发者ID:jomann09,项目名称:psutil,代码行数:11,代码来源:test_posix.py

示例7: test_cpu_count_none

 def test_cpu_count_none(self):
     # https://github.com/giampaolo/psutil/issues/1085
     for val in (-1, 0, None):
         with mock.patch('psutil._psplatform.cpu_count_logical',
                         return_value=val) as m:
             self.assertIsNone(psutil.cpu_count())
             assert m.called
         with mock.patch('psutil._psplatform.cpu_count_physical',
                         return_value=val) as m:
             self.assertIsNone(psutil.cpu_count(logical=False))
             assert m.called
开发者ID:mabuaita,项目名称:ops,代码行数:11,代码来源:test_system.py

示例8: test_name_long

 def test_name_long(self):
     # On UNIX the kernel truncates the name to the first 15
     # characters. In such a case psutil tries to determine the
     # full name from the cmdline.
     name = "long-program-name"
     cmdline = ["long-program-name-extended", "foo", "bar"]
     with mock.patch("psutil._psplatform.Process.name",
                     return_value=name):
         with mock.patch("psutil._psplatform.Process.cmdline",
                         return_value=cmdline):
             p = psutil.Process()
             self.assertEqual(p.name(), "long-program-name-extended")
开发者ID:jomann09,项目名称:psutil,代码行数:12,代码来源:test_posix.py

示例9: test_cmdline_mocked

 def test_cmdline_mocked(self):
     # see: https://github.com/giampaolo/psutil/issues/639
     p = psutil.Process()
     fake_file = io.StringIO(u('foo\x00bar\x00'))
     with mock.patch('psutil._pslinux.open',
                     return_value=fake_file, create=True) as m:
         p.cmdline() == ['foo', 'bar']
         assert m.called
     fake_file = io.StringIO(u('foo\x00bar\x00\x00'))
     with mock.patch('psutil._pslinux.open',
                     return_value=fake_file, create=True) as m:
         p.cmdline() == ['foo', 'bar', '']
         assert m.called
开发者ID:4sp1r3,项目名称:psutil,代码行数:13,代码来源:test_linux.py

示例10: test_process_iter

    def test_process_iter(self):
        self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()])
        sproc = get_test_subprocess()
        self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()])
        p = psutil.Process(sproc.pid)
        p.kill()
        p.wait()
        self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()])

        with mock.patch("psutil.Process", side_effect=psutil.NoSuchProcess(os.getpid())):
            self.assertEqual(list(psutil.process_iter()), [])
        with mock.patch("psutil.Process", side_effect=psutil.AccessDenied(os.getpid())):
            with self.assertRaises(psutil.AccessDenied):
                list(psutil.process_iter())
开发者ID:DipoChiang,项目名称:DjangoCourse,代码行数:14,代码来源:test_system.py

示例11: test_net_if_stats_enodev

 def test_net_if_stats_enodev(self):
     # See: https://github.com/giampaolo/psutil/issues/1279
     with mock.patch('psutil._psutil_posix.net_if_mtu',
                     side_effect=OSError(errno.ENODEV, "")) as m:
         ret = psutil.net_if_stats()
         self.assertEqual(ret, {})
         assert m.called
开发者ID:eomsoft,项目名称:teleport,代码行数:7,代码来源:test_system.py

示例12: test_num_handles

 def test_num_handles(self):
     num_handles = psutil.Process(self.pid).num_handles()
     with mock.patch("psutil._psplatform.cext.proc_num_handles",
                     side_effect=OSError(errno.EPERM, "msg")) as fun:
         self.assertEqual(psutil.Process(self.pid).num_handles(),
                          num_handles)
         assert fun.called
开发者ID:Colorado4Wheeler,项目名称:Mac-Commander,代码行数:7,代码来源:test_windows.py

示例13: test_os_waitpid_bad_ret_status

 def test_os_waitpid_bad_ret_status(self):
     # Simulate os.waitpid() returning a bad status.
     with mock.patch("psutil._psposix.os.waitpid",
                     return_value=(1, -1)) as m:
         self.assertRaises(ValueError,
                           psutil._psposix.wait_pid, os.getpid())
         assert m.called
开发者ID:jomann09,项目名称:psutil,代码行数:7,代码来源:test_posix.py

示例14: test_isfile_strict

 def test_isfile_strict(self):
     from psutil._common import isfile_strict
     this_file = os.path.abspath(__file__)
     assert isfile_strict(this_file)
     assert not isfile_strict(os.path.dirname(this_file))
     with mock.patch('psutil._common.os.stat',
                     side_effect=OSError(errno.EPERM, "foo")):
         self.assertRaises(OSError, isfile_strict, this_file)
     with mock.patch('psutil._common.os.stat',
                     side_effect=OSError(errno.EACCES, "foo")):
         self.assertRaises(OSError, isfile_strict, this_file)
     with mock.patch('psutil._common.os.stat',
                     side_effect=OSError(errno.EINVAL, "foo")):
         assert not isfile_strict(this_file)
     with mock.patch('psutil._common.stat.S_ISREG', return_value=False):
         assert not isfile_strict(this_file)
开发者ID:nicolargo,项目名称:psutil,代码行数:16,代码来源:test_misc.py

示例15: test_no_procfs_on_import

    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')
开发者ID:4sp1r3,项目名称:psutil,代码行数:60,代码来源:test_linux.py


注:本文中的psutil.tests.mock.patch函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。