Ejemplo n.º 1
0
    def test_connections(self):
        def create_socket(family, type):
            sock = socket.socket(family, type)
            sock.bind(('', 0))
            if type == socket.SOCK_STREAM:
                sock.listen(1)
            return sock

        socks = []
        socks.append(create_socket(socket.AF_INET, socket.SOCK_STREAM))
        socks.append(create_socket(socket.AF_INET, socket.SOCK_DGRAM))
        if supports_ipv6():
            socks.append(create_socket(socket.AF_INET6, socket.SOCK_STREAM))
            socks.append(create_socket(socket.AF_INET6, socket.SOCK_DGRAM))
        if hasattr(socket, 'AF_UNIX'):
            safe_rmpath(TESTFN)
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            s.bind(TESTFN)
            s.listen(1)
            socks.append(s)
        kind = 'all'
        # TODO: UNIX sockets are temporarily implemented by parsing
        # 'pfiles' cmd  output; we don't want that part of the code to
        # be executed.
        if SUNOS:
            kind = 'inet'
        try:
            self.execute('connections', kind=kind)
        finally:
            for s in socks:
                s.close()
Ejemplo n.º 2
0
  def test_when_invalid_hardlink_and_coursier_cache_should_trigger_resolve(self):
    jar_lib = self._make_junit_target()
    with self._temp_workdir():
      with temporary_dir() as couriser_cache_dir:
        self.set_options_for_scope('coursier', cache_dir=couriser_cache_dir)

        context = self.context(target_roots=[jar_lib])
        task = self.execute(context)
        compile_classpath = context.products.get_data('compile_classpath')

        jar_cp = compile_classpath.get_for_target(jar_lib)

        # └─ junit:junit:4.12
        #    └─ org.hamcrest:hamcrest-core:1.3
        self.assertEqual(2, len(jar_cp))


        # Take a sample jar path, remove it, then call the task again, it should invoke coursier again
        conf, path = jar_cp[0]

        # Remove the hard link under .pants.d/
        safe_rmpath(path)

        # Remove coursier's cache
        safe_rmtree(couriser_cache_dir)

        util.execute_runner = MagicMock()

        # Ignore any error because runjava may fail due to undefined behavior
        try:
          task.execute()
        except TaskError:
          pass

        util.execute_runner.assert_called()
Ejemplo n.º 3
0
    def test_open_files_mode(self):
        def get_test_file():
            p = psutil.Process()
            giveup_at = time.time() + 2
            while True:
                for file in p.open_files():
                    if file.path == os.path.abspath(TESTFN):
                        return file
                    elif time.time() > giveup_at:
                        break
            raise RuntimeError("timeout looking for test file")

        #
        with open(TESTFN, "w"):
            self.assertEqual(get_test_file().mode, "w")
        with open(TESTFN, "r"):
            self.assertEqual(get_test_file().mode, "r")
        with open(TESTFN, "a"):
            self.assertEqual(get_test_file().mode, "a")
        #
        with open(TESTFN, "r+"):
            self.assertEqual(get_test_file().mode, "r+")
        with open(TESTFN, "w+"):
            self.assertEqual(get_test_file().mode, "r+")
        with open(TESTFN, "a+"):
            self.assertEqual(get_test_file().mode, "a+")
        # note: "x" bit is not supported
        if PY3:
            safe_rmpath(TESTFN)
            with open(TESTFN, "x"):
                self.assertEqual(get_test_file().mode, "w")
            safe_rmpath(TESTFN)
            with open(TESTFN, "x+"):
                self.assertEqual(get_test_file().mode, "r+")
Ejemplo n.º 4
0
  def test_when_invalid_hardlink_and_coursier_cache_should_trigger_resolve(self):
    jar_lib = self._make_junit_target()
    with self._temp_workdir():
      with temporary_dir() as couriser_cache_dir:
        self.set_options_for_scope('coursier', cache_dir=couriser_cache_dir)

        context = self.context(target_roots=[jar_lib])
        task = self.execute(context)
        compile_classpath = context.products.get_data('compile_classpath')

        jar_cp = compile_classpath.get_for_target(jar_lib)

        # └─ junit:junit:4.12
        #    └─ org.hamcrest:hamcrest-core:1.3
        self.assertEqual(2, len(jar_cp))


        # Take a sample jar path, remove it, then call the task again, it should invoke coursier again
        conf, path = jar_cp[0]

        # Remove the hard link under .pants.d/
        safe_rmpath(path)

        # Remove coursier's cache
        safe_rmtree(couriser_cache_dir)

        util.execute_runner = MagicMock()

        # Ignore any error because runjava may fail due to undefined behavior
        try:
          task.execute()
        except TaskError:
          pass

        util.execute_runner.assert_called()
Ejemplo n.º 5
0
def main():
    setup()
    usage = "python3 -m psutil.tests [opts] [test-name]"
    parser = optparse.OptionParser(usage=usage, description="run unit tests")
    parser.add_option("--last-failed",
                      action="store_true",
                      default=False,
                      help="only run last failed tests")
    parser.add_option("--parallel",
                      action="store_true",
                      default=False,
                      help="run tests in parallel")
    opts, args = parser.parse_args()

    if not opts.last_failed:
        safe_rmpath(FAILED_TESTS_FNAME)

    # loader
    loader = TestLoader()
    if args:
        if len(args) > 1:
            parser.print_usage()
            return sys.exit(1)
        else:
            suite = loader.from_name(args[0])
    elif opts.last_failed:
        suite = loader.last_failed()
    else:
        suite = loader.all()

    if CI_TESTING:
        print_sysinfo()
    runner = get_runner(opts.parallel)
    runner.run(suite)
Ejemplo n.º 6
0
def main():
    _setup()
    usage = "python3 -m psutil.tests [opts] [test-name]"
    parser = optparse.OptionParser(usage=usage, description="run unit tests")
    parser.add_option("--last-failed",
                      action="store_true", default=False,
                      help="only run last failed tests")
    parser.add_option("--parallel",
                      action="store_true", default=False,
                      help="run tests in parallel")
    opts, args = parser.parse_args()

    if not opts.last_failed:
        safe_rmpath(FAILED_TESTS_FNAME)

    # test-by-name
    if args:
        if len(args) > 1:
            parser.print_usage()
            return sys.exit(1)
        return runner.run_from_name(args[0])
    elif opts.last_failed:
        runner.run_last_failed()
    elif not opts.parallel:
        runner.run()
    # parallel
    elif concurrencytest is None:
        print_color("concurrencytest module is not installed; "
                    "running serial tests instead", "red")
        runner.run()
    elif NWORKERS == 1:
        print_color("only 1 CPU; running serial tests instead", "red")
        runner.run()
    else:
        runner.run_parallel()
Ejemplo n.º 7
0
 def _finalize(self, success):
     if success:
         safe_rmpath(FAILED_TESTS_FNAME)
     else:
         self._write_last_failed()
         print_color("FAILED", "red")
         sys.exit(1)
Ejemplo n.º 8
0
    def test_connections(self):
        def create_socket(family, type):
            sock = socket.socket(family, type)
            sock.bind(('', 0))
            if type == socket.SOCK_STREAM:
                sock.listen(1)
            return sock

        socks = []
        socks.append(create_socket(socket.AF_INET, socket.SOCK_STREAM))
        socks.append(create_socket(socket.AF_INET, socket.SOCK_DGRAM))
        if supports_ipv6():
            socks.append(create_socket(socket.AF_INET6, socket.SOCK_STREAM))
            socks.append(create_socket(socket.AF_INET6, socket.SOCK_DGRAM))
        if hasattr(socket, 'AF_UNIX'):
            safe_rmpath(TESTFN)
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            s.bind(TESTFN)
            s.listen(1)
            socks.append(s)
        kind = 'all'
        # TODO: UNIX sockets are temporarily implemented by parsing
        # 'pfiles' cmd  output; we don't want that part of the code to
        # be executed.
        if SUNOS:
            kind = 'inet'
        try:
            self.execute(self.proc.connections, kind)
        finally:
            for s in socks:
                s.close()
Ejemplo n.º 9
0
 def tearDown(self):
     safe_rmpath(TESTFN)
     reap_children()
     if not NETBSD:
         # Make sure we closed all resources.
         # NetBSD opens a UNIX socket to /var/log/run.
         cons = thisproc.connections(kind='all')
         assert not cons, cons
Ejemplo n.º 10
0
 def tearDown(self):
     safe_rmpath(TESTFN)
     reap_children()
     if not NETBSD:
         # Make sure we closed all resources.
         # NetBSD opens a UNIX socket to /var/log/run.
         cons = thisproc.connections(kind='all')
         assert not cons, cons
Ejemplo n.º 11
0
 def _exit(self, success):
     if success:
         cprint("SUCCESS", "green", bold=True)
         safe_rmpath(FAILED_TESTS_FNAME)
         sys.exit(0)
     else:
         cprint("FAILED", "red", bold=True)
         self._write_last_failed()
         sys.exit(1)
Ejemplo n.º 12
0
 def test_disk_usage_unicode(self):
     # See: https://github.com/giampaolo/psutil/issues/416
     if ASCII_FS:
         with self.assertRaises(UnicodeEncodeError):
             psutil.disk_usage(TESTFN_UNICODE)
     else:
         safe_rmpath(TESTFN_UNICODE)
         self.addCleanup(safe_rmpath, TESTFN_UNICODE)
         os.mkdir(TESTFN_UNICODE)
         psutil.disk_usage(TESTFN_UNICODE)
Ejemplo n.º 13
0
def main():
    global TOKEN
    parser = argparse.ArgumentParser(description='GitHub wheels downloader')
    parser.add_argument('--tokenfile', required=True)
    args = parser.parse_args()
    with open(os.path.expanduser(args.tokenfile)) as f:
        TOKEN = f.read().strip()
    try:
        run()
    finally:
        safe_rmpath(OUTFILE)
Ejemplo n.º 14
0
def subprocess_supports_unicode(name):
    """Return True if both the fs and the subprocess module can
    deal with a unicode file name.
    """
    if PY3:
        return True
    try:
        safe_rmpath(name)
        create_exe(name)
        get_test_subprocess(cmd=[name])
    except UnicodeEncodeError:
        return False
    else:
        reap_children()
        return True
Ejemplo n.º 15
0
def save_failed_tests(result):
    if result.wasSuccessful():
        return safe_rmpath(FAILED_TESTS_FNAME)
    with open(FAILED_TESTS_FNAME, 'wt') as f:
        for t in result.errors + result.failures:
            tname = str(t[0])
            f.write(tname + '\n')
Ejemplo n.º 16
0
def save_failed_tests(result):
    if result.wasSuccessful():
        return safe_rmpath(FAILED_TESTS_FNAME)
    with open(FAILED_TESTS_FNAME, 'wt') as f:
        for t in result.errors + result.failures:
            tname = str(t[0])
            f.write(tname + '\n')
Ejemplo n.º 17
0
def main():
    global TOKEN
    parser = argparse.ArgumentParser(description='GitHub wheels downloader')
    parser.add_argument('--token')
    parser.add_argument('--tokenfile')
    args = parser.parse_args()

    if args.tokenfile:
        with open(os.path.expanduser(args.tokenfile)) as f:
            TOKEN = f.read().strip()
    elif args.token:
        TOKEN = args.token
    else:
        return sys.exit('specify --token or --tokenfile args')

    try:
        run()
    finally:
        safe_rmpath(OUTFILE)
Ejemplo n.º 18
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
    sproc = None
    testfn = get_testfn(suffix=suffix)
    try:
        safe_rmpath(testfn)
        create_exe(testfn)
        sproc = spawn_testproc(cmd=[testfn])
    except UnicodeEncodeError:
        return False
    else:
        return True
    finally:
        if sproc is not None:
            terminate(sproc)
        safe_rmpath(testfn)
Ejemplo n.º 19
0
 def test_safe_rmpath(self):
     # test file is removed
     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
Ejemplo n.º 20
0
 def test_safe_rmpath(self):
     # test file is removed
     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
Ejemplo n.º 21
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)
Ejemplo n.º 22
0
 def tearDown(self):
     safe_rmpath(TESTFN)
     reap_children()
     # make sure we closed all resources
     cons = psutil.Process().connections(kind='all')
     assert not cons, cons
Ejemplo n.º 23
0
 def test_disk_usage_unicode(self):
     # see: https://github.com/giampaolo/psutil/issues/416
     safe_rmpath(TESTFN_UNICODE)
     self.addCleanup(safe_rmpath, TESTFN_UNICODE)
     os.mkdir(TESTFN_UNICODE)
     psutil.disk_usage(TESTFN_UNICODE)
Ejemplo n.º 24
0
 def setUp(self):
     safe_rmpath(TESTFN)
Ejemplo n.º 25
0
 def test_open_files(self):
     safe_rmpath(TESTFN)  # needed after UNIX socket test has run
     with open(TESTFN, 'w'):
         self.execute('open_files')
Ejemplo n.º 26
0
 def tearDown(self):
     reap_children()
     safe_rmpath(self.funky_name)
Ejemplo n.º 27
0
 def setUp(self):
     safe_rmpath(self.funky_name)
Ejemplo n.º 28
0
 def setUp(self):
     safe_rmpath(TESTFN)
Ejemplo n.º 29
0
 def tearDown(self):
     safe_rmpath(TESTFN)
Ejemplo n.º 30
0
 def test_disk_usage_unicode(self):
     # see: https://github.com/giampaolo/psutil/issues/416
     safe_rmpath(TESTFN_UNICODE)
     self.addCleanup(safe_rmpath, TESTFN_UNICODE)
     os.mkdir(TESTFN_UNICODE)
     psutil.disk_usage(TESTFN_UNICODE)
Ejemplo n.º 31
0
 def setUp(self):
     safe_rmpath(TESTFN)
     if not NETBSD:
         # NetBSD opens a UNIX socket to /var/log/run.
         cons = thisproc.connections(kind='all')
         assert not cons, cons
Ejemplo n.º 32
0
 def tearDown(self):
     safe_rmpath(TESTFN)
Ejemplo n.º 33
0
 def tearDownClass(cls):
     safe_rmpath(cls.funky_name)
Ejemplo n.º 34
0
 def setUp(self):
     safe_rmpath(TESTFN)
     if not (NETBSD or FREEBSD):
         # process opens a UNIX socket to /var/log/run.
         cons = thisproc.connections(kind='all')
         assert not cons, cons
Ejemplo n.º 35
0
 def test_open_files(self):
     safe_rmpath(TESTFN)  # needed after UNIX socket test has run
     with open(TESTFN, 'w'):
         self.execute(self.proc.open_files)