Пример #1
0
 def test_bind_unix_socket(self):
     name = get_testfn()
     sock = bind_unix_socket(name)
     with contextlib.closing(sock):
         self.assertEqual(sock.family, socket.AF_UNIX)
         self.assertEqual(sock.type, socket.SOCK_STREAM)
         self.assertEqual(sock.getsockname(), name)
         assert os.path.exists(name)
         assert stat.S_ISSOCK(os.stat(name).st_mode)
     # UDP
     name = get_testfn()
     sock = bind_unix_socket(name, type=socket.SOCK_DGRAM)
     with contextlib.closing(sock):
         self.assertEqual(sock.type, socket.SOCK_DGRAM)
Пример #2
0
    def test_disk_usage(self):
        usage = psutil.disk_usage(os.getcwd())
        self.assertEqual(usage._fields, ('total', 'used', 'free', 'percent'))

        assert usage.total > 0, usage
        assert usage.used > 0, usage
        assert usage.free > 0, usage
        assert usage.total > usage.used, usage
        assert usage.total > usage.free, usage
        assert 0 <= usage.percent <= 100, usage.percent
        if hasattr(shutil, 'disk_usage'):
            # py >= 3.3, see: http://bugs.python.org/issue12442
            shutil_usage = shutil.disk_usage(os.getcwd())
            tolerance = 5 * 1024 * 1024  # 5MB
            self.assertEqual(usage.total, shutil_usage.total)
            self.assertAlmostEqual(usage.free,
                                   shutil_usage.free,
                                   delta=tolerance)
            self.assertAlmostEqual(usage.used,
                                   shutil_usage.used,
                                   delta=tolerance)

        # if path does not exist OSError ENOENT is expected across
        # all platforms
        fname = get_testfn()
        with self.assertRaises(FileNotFoundError):
            psutil.disk_usage(fname)
Пример #3
0
 def test_chdir(self):
     testfn = get_testfn()
     base = os.getcwd()
     os.mkdir(testfn)
     with chdir(testfn):
         self.assertEqual(os.getcwd(), os.path.join(base, testfn))
     self.assertEqual(os.getcwd(), base)
Пример #4
0
 def test_unix(self):
     testfn = get_testfn()
     server, client = unix_socketpair(testfn)
     try:
         cons = thisproc.connections(kind='unix')
         assert not (cons[0].laddr and cons[0].raddr)
         assert not (cons[1].laddr and cons[1].raddr)
         if NETBSD or FREEBSD:
             # On NetBSD creating a UNIX socket will cause
             # a UNIX connection to  /var/run/log.
             cons = [c for c in cons if c.raddr != '/var/run/log']
             if CIRRUS:
                 cons = [c for c in cons if c.fd in
                         (server.fileno(), client.fileno())]
         self.assertEqual(len(cons), 2, msg=cons)
         if LINUX or FREEBSD or SUNOS:
             # remote path is never set
             self.assertEqual(cons[0].raddr, "")
             self.assertEqual(cons[1].raddr, "")
             # one local address should though
             self.assertEqual(testfn, cons[0].laddr or cons[1].laddr)
         elif OPENBSD:
             # No addresses whatsoever here.
             for addr in (cons[0].laddr, cons[0].raddr,
                          cons[1].laddr, cons[1].raddr):
                 self.assertEqual(addr, "")
         else:
             # On other systems either the laddr or raddr
             # of both peers are set.
             self.assertEqual(cons[0].laddr or cons[1].laddr, testfn)
             self.assertEqual(cons[0].raddr or cons[1].raddr, testfn)
     finally:
         server.close()
         client.close()
Пример #5
0
 def test_unix_socketpair(self):
     p = psutil.Process()
     num_fds = p.num_fds()
     assert not p.connections(kind='unix')
     name = get_testfn()
     server, client = unix_socketpair(name)
     try:
         assert os.path.exists(name)
         assert stat.S_ISSOCK(os.stat(name).st_mode)
         self.assertEqual(p.num_fds() - num_fds, 2)
         self.assertEqual(len(p.connections(kind='unix')), 2)
         self.assertEqual(server.getsockname(), name)
         self.assertEqual(client.getpeername(), name)
     finally:
         client.close()
         server.close()
Пример #6
0
 def test_proc_connections(self):
     suffix = os.path.basename(self.funky_name)
     name = get_testfn(suffix=suffix)
     try:
         sock = bind_unix_socket(name)
     except UnicodeEncodeError:
         if PY3:
             raise
         else:
             raise unittest.SkipTest("not supported")
     with closing(sock):
         conn = psutil.Process().connections('unix')[0]
         self.assertIsInstance(conn.laddr, str)
         # AF_UNIX addr not set on OpenBSD
         if not OPENBSD and not CIRRUS:  # XXX
             self.assertEqual(conn.laddr, name)
Пример #7
0
def subprocess_supports_unicode(suffix):
    """Return True if both the fs and the subprocess module can
    deal with a unicode file name.
    """
    if PY3:
        return True
    name = get_testfn(suffix=suffix)
    try:
        safe_rmpath(name)
        create_exe(name)
        get_test_subprocess(cmd=[name])
    except UnicodeEncodeError:
        return False
    else:
        return True
    finally:
        reap_children()
Пример #8
0
 def test_safe_rmpath(self):
     # test file is removed
     testfn = get_testfn()
     open(testfn, 'w').close()
     safe_rmpath(testfn)
     assert not os.path.exists(testfn)
     # test no exception if path does not exist
     safe_rmpath(testfn)
     # test dir is removed
     os.mkdir(testfn)
     safe_rmpath(testfn)
     assert not os.path.exists(testfn)
     # test other exceptions are raised
     with mock.patch('psutil.tests.os.stat',
                     side_effect=OSError(errno.EINVAL, "")) as m:
         with self.assertRaises(OSError):
             safe_rmpath(testfn)
         assert m.called
Пример #9
0
def subprocess_supports_unicode(suffix):
    """Return True if both the fs and the subprocess module can
    deal with a unicode file name.
    """
    if PY3:
        return True
    name = get_testfn(suffix=suffix)
    sproc = None
    try:
        safe_rmpath(name)
        create_exe(name)
        sproc = get_test_subprocess(cmd=[name])
    except UnicodeEncodeError:
        return False
    else:
        return True
    finally:
        if sproc is not None:
            terminate(sproc)
Пример #10
0
def try_unicode(suffix):
    """Return True if both the fs and the subprocess module can
    deal with a unicode file name.
    """
    sproc = None
    testfn = get_testfn(suffix=suffix)
    try:
        safe_rmpath(testfn)
        create_exe(testfn)
        sproc = spawn_testproc(cmd=[testfn])
        shutil.copyfile(testfn, testfn + '-2')
        safe_rmpath(testfn + '-2')
    except (UnicodeEncodeError, IOError):
        return False
    else:
        return True
    finally:
        if sproc is not None:
            terminate(sproc)
        safe_rmpath(testfn)
Пример #11
0
    def test_multi_sockets_procs(self):
        # Creates multiple sub processes, each creating different
        # sockets. For each process check that proc.connections()
        # and net_connections() return the same results.
        # This is done mainly to check whether net_connections()'s
        # pid is properly set, see:
        # https://github.com/giampaolo/psutil/issues/1013
        with create_sockets() as socks:
            expected = len(socks)
        pids = []
        times = 10
        fnames = []
        for i in range(times):
            fname = get_testfn()
            fnames.append(fname)
            src = textwrap.dedent("""\
                import time, os
                from psutil.tests import create_sockets, cleanup_test_files
                with create_sockets():
                    with open(r'%s', 'w') as f:
                        f.write("hello")
                    # 2 UNIX test socket files are created
                    cleanup_test_files()
                    time.sleep(60)
                """ % fname)
            sproc = pyrun(src)
            pids.append(sproc.pid)

        # sync
        for fname in fnames:
            wait_for_file(fname)

        syscons = [
            x for x in psutil.net_connections(kind='all') if x.pid in pids
        ]
        for pid in pids:
            self.assertEqual(len([x for x in syscons if x.pid == pid]),
                             expected)
            p = psutil.Process(pid)
            self.assertEqual(len(p.connections('all')), expected)
Пример #12
0
    def test_net_connections(self):
        def find_sock(cons):
            for conn in cons:
                if os.path.basename(conn.laddr).startswith(TESTFN_PREFIX):
                    return conn
            raise ValueError("connection not found")

        suffix = os.path.basename(self.funky_name)
        name = get_testfn(suffix=suffix)
        try:
            sock = bind_unix_socket(name)
        except UnicodeEncodeError:
            if PY3:
                raise
            else:
                raise unittest.SkipTest("not supported")
        with closing(sock):
            cons = psutil.net_connections(kind='unix')
            # AF_UNIX addr not set on OpenBSD
            if not OPENBSD:
                conn = find_sock(cons)
                self.assertIsInstance(conn.laddr, str)
                self.assertEqual(conn.laddr, name)
Пример #13
0
    def test_combos(self):
        def check_conn(proc, conn, family, type, laddr, raddr, status, kinds):
            all_kinds = ("all", "inet", "inet4", "inet6", "tcp", "tcp4",
                         "tcp6", "udp", "udp4", "udp6")
            self.check_connection_ntuple(conn)
            self.assertEqual(conn.family, family)
            self.assertEqual(conn.type, type)
            self.assertEqual(conn.laddr, laddr)
            self.assertEqual(conn.raddr, raddr)
            self.assertEqual(conn.status, status)
            for kind in all_kinds:
                cons = proc.connections(kind=kind)
                if kind in kinds:
                    assert cons
                else:
                    assert not cons, cons
            # compare against system-wide connections
            # XXX Solaris can't retrieve system-wide UNIX
            # sockets.
            if HAS_CONNECTIONS_UNIX:
                self.compare_procsys_connections(proc.pid, [conn])

        tcp_template = textwrap.dedent("""
            import socket, time
            s = socket.socket($family, socket.SOCK_STREAM)
            s.bind(('$addr', 0))
            s.listen(5)
            with open('$testfn', 'w') as f:
                f.write(str(s.getsockname()[:2]))
            time.sleep(60)
        """)

        udp_template = textwrap.dedent("""
            import socket, time
            s = socket.socket($family, socket.SOCK_DGRAM)
            s.bind(('$addr', 0))
            with open('$testfn', 'w') as f:
                f.write(str(s.getsockname()[:2]))
            time.sleep(60)
        """)

        # must be relative on Windows
        testfile = os.path.basename(get_testfn(dir=os.getcwd()))
        tcp4_template = string.Template(tcp_template).substitute(
            family=int(AF_INET), addr="127.0.0.1", testfn=testfile)
        udp4_template = string.Template(udp_template).substitute(
            family=int(AF_INET), addr="127.0.0.1", testfn=testfile)
        tcp6_template = string.Template(tcp_template).substitute(
            family=int(AF_INET6), addr="::1", testfn=testfile)
        udp6_template = string.Template(udp_template).substitute(
            family=int(AF_INET6), addr="::1", testfn=testfile)

        # launch various subprocess instantiating a socket of various
        # families and types to enrich psutil results
        tcp4_proc = pyrun(tcp4_template)
        tcp4_addr = eval(wait_for_file(testfile))
        udp4_proc = pyrun(udp4_template)
        udp4_addr = eval(wait_for_file(testfile))
        if supports_ipv6():
            tcp6_proc = pyrun(tcp6_template)
            tcp6_addr = eval(wait_for_file(testfile))
            udp6_proc = pyrun(udp6_template)
            udp6_addr = eval(wait_for_file(testfile))
        else:
            tcp6_proc = None
            udp6_proc = None
            tcp6_addr = None
            udp6_addr = None

        for p in thisproc.children():
            cons = p.connections()
            self.assertEqual(len(cons), 1)
            for conn in cons:
                # TCP v4
                if p.pid == tcp4_proc.pid:
                    check_conn(p, conn, AF_INET, SOCK_STREAM, tcp4_addr, (),
                               psutil.CONN_LISTEN,
                               ("all", "inet", "inet4", "tcp", "tcp4"))
                # UDP v4
                elif p.pid == udp4_proc.pid:
                    check_conn(p, conn, AF_INET, SOCK_DGRAM, udp4_addr, (),
                               psutil.CONN_NONE,
                               ("all", "inet", "inet4", "udp", "udp4"))
                # TCP v6
                elif p.pid == getattr(tcp6_proc, "pid", None):
                    check_conn(p, conn, AF_INET6, SOCK_STREAM, tcp6_addr, (),
                               psutil.CONN_LISTEN,
                               ("all", "inet", "inet6", "tcp", "tcp6"))
                # UDP v6
                elif p.pid == getattr(udp6_proc, "pid", None):
                    check_conn(p, conn, AF_INET6, SOCK_DGRAM, udp6_addr, (),
                               psutil.CONN_NONE,
                               ("all", "inet", "inet6", "udp", "udp6"))
Пример #14
0
 def test_unix_udp(self):
     with closing(bind_unix_socket(get_testfn(), type=SOCK_STREAM)) as sock:
         conn = self.check_socket(sock)
         assert not conn.raddr
         self.assertEqual(conn.status, psutil.CONN_NONE)
Пример #15
0
 def setUpClass(cls):
     cls.funky_name = get_testfn(suffix=cls.funky_suffix)
     create_exe(cls.funky_name)
Пример #16
0
 def test_wait_for_file_empty(self):
     testfn = get_testfn()
     with open(testfn, 'w'):
         pass
     wait_for_file(testfn, empty=True)
     assert not os.path.exists(testfn)
Пример #17
0
 def test_safe_mkdir(self):
     testfn = get_testfn()
     safe_mkdir(testfn)
     assert os.path.isdir(testfn)
     safe_mkdir(testfn)
     assert os.path.isdir(testfn)
Пример #18
0
 def test_wait_for_file_no_delete(self):
     testfn = get_testfn()
     with open(testfn, 'w') as f:
         f.write('foo')
     wait_for_file(testfn, delete=False)
     assert os.path.exists(testfn)
Пример #19
0
 def test_wait_for_file_no_file(self):
     testfn = get_testfn()
     with mock.patch('psutil.tests.retry.__iter__', return_value=iter([0])):
         self.assertRaises(IOError, wait_for_file, testfn)
Пример #20
0
 def test_open_files(self):
     with open(get_testfn(), 'w'):
         self.execute(self.proc.open_files)
Пример #21
0
 def test_wait_for_file(self):
     testfn = get_testfn()
     with open(testfn, 'w') as f:
         f.write('foo')
     wait_for_file(testfn)
     assert not os.path.exists(testfn)