Python os.stat_result() Examples

The following are 30 code examples of os.stat_result(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: rewrite.py    From pytest with MIT License 6 votes vote down vote up
def _write_pyc(
        state: "AssertionState",
        co: types.CodeType,
        source_stat: os.stat_result,
        pyc: Path,
    ) -> bool:
        try:
            with atomic_write(fspath(pyc), mode="wb", overwrite=True) as fp:
                _write_pyc_fp(fp, source_stat, co)
        except OSError as e:
            state.trace("error writing pyc file at {}: {}".format(pyc, e))
            # we ignore any failure to write the cache file
            # there are many reasons, permission-denied, pycache dir being a
            # file etc.
            return False
        return True 
Example #2
Source File: test_domain_substitution.py    From ungoogled-chromium with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_update_timestamp():
    with tempfile.TemporaryDirectory() as tmpdirname:
        path = Path(tmpdirname, 'tmp_update_timestamp')
        path.touch()
        orig_stats: os.stat_result = path.stat()

        # Add delta to timestamp
        with domain_substitution._update_timestamp(path, set_new=True):
            with path.open('w') as fileobj:
                fileobj.write('foo')

        new_stats: os.stat_result = path.stat()
        assert orig_stats.st_atime_ns != new_stats.st_atime_ns
        assert orig_stats.st_mtime_ns != new_stats.st_mtime_ns

        # Remove delta from timestamp
        with domain_substitution._update_timestamp(path, set_new=False):
            with path.open('w') as fileobj:
                fileobj.write('bar')

        new_stats: os.stat_result = path.stat()
        assert orig_stats.st_atime_ns == new_stats.st_atime_ns
        assert orig_stats.st_mtime_ns == new_stats.st_mtime_ns 
Example #3
Source File: test_cftp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_newSingleDigitDayOfMonth(self):
        """
        A file with a high-resolution timestamp which falls on a day of the
        month which can be represented by one decimal digit is formatted with
        one padding 0 to preserve the columns which come after it.
        """
        # A point about three months in the past, tweaked to fall on the first
        # of a month so we test the case we want to test.
        then = self.now - (60 * 60 * 24 * 31 * 3) + (60 * 60 * 24 * 4)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Sep 01 17:33 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Sep 02 09:33 foo') 
Example #4
Source File: test_cftp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_localeIndependent(self):
        """
        The month name in the date is locale independent.
        """
        # A point about three months in the past.
        then = self.now - (60 * 60 * 24 * 31 * 3)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        # Fake that we're in a language where August is not Aug (e.g.: Spanish)
        currentLocale = locale.getlocale()
        locale.setlocale(locale.LC_ALL, "es_AR.UTF8")
        self.addCleanup(locale.setlocale, locale.LC_ALL, currentLocale)

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Aug 28 17:33 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Aug 29 09:33 foo')

    # If alternate locale is not available, the previous test will be
    # skipped, please install this locale for it to run 
Example #5
Source File: test_cftp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_oldSingleDigitDayOfMonth(self):
        """
        A file with a high-resolution timestamp which falls on a day of the
        month which can be represented by one decimal digit is formatted with
        one padding 0 to preserve the columns which come after it.
        """
        # A point about 7 months in the past, tweaked to fall on the first of a
        # month so we test the case we want to test.
        then = self.now - (60 * 60 * 24 * 31 * 7) + (60 * 60 * 24 * 5)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 May 01  1973 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 May 02  1973 foo') 
Example #6
Source File: test_cftp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_oldSingleDigitDayOfMonth(self):
        """
        A file with a high-resolution timestamp which falls on a day of the
        month which can be represented by one decimal digit is formatted with
        one padding 0 to preserve the columns which come after it.
        """
        # A point about 7 months in the past, tweaked to fall on the first of a
        # month so we test the case we want to test.
        then = self.now - (60 * 60 * 24 * 31 * 7) + (60 * 60 * 24 * 5)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 May 01  1973 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 May 02  1973 foo') 
Example #7
Source File: test_cftp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_newSingleDigitDayOfMonth(self):
        """
        A file with a high-resolution timestamp which falls on a day of the
        month which can be represented by one decimal digit is formatted with
        one padding 0 to preserve the columns which come after it.
        """
        # A point about three months in the past, tweaked to fall on the first
        # of a month so we test the case we want to test.
        then = self.now - (60 * 60 * 24 * 31 * 3) + (60 * 60 * 24 * 4)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Sep 01 17:33 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Sep 02 09:33 foo') 
Example #8
Source File: test_watcher.py    From galaxy_blizzard_plugin with MIT License 6 votes vote down vote up
def mock_stat(mocker):
    def function():
        a_stat = list(os.stat(__file__))
        stat_results = []
        for x in range(5):
            a_stat[-2] += 1
            stat_results.append(os.stat_result(a_stat))
        mocker.patch('os.stat', side_effect=stat_results)
    return function


# TODO
# def test_watcher(waiter, mock_stat):
#     mock_stat()
#     def 
#     file_watcher = FileWatcher()
#     event = file_watcher.get_event()
#     assert event.is_set()
#     task = asyncio.create_task(waiter()(event))
#     await task
#     assert not event.is_set() 
Example #9
Source File: rpmcapsule.py    From conary with Apache License 2.0 6 votes vote down vote up
def rpmExpandMacro(val):
    if getattr(rpm, '_rpm', ''):
        rawRpmModulePath = rpm._rpm.__file__
    else:
        rawRpmModulePath = rpm.__file__
    sonames = [ x[1] for x in elf.inspect(rawRpmModulePath)[0]
                    if x[0] == 'soname']
    rpmLibs = [ x for x in sonames if re.match('librpm[-\.].*so', x) ]
    assert(len(rpmLibs) == 1)
    librpm = ctypes.CDLL(rpmLibs[0])
    librpm.expandMacros.argtypes = (c_void_p, c_void_p, c_void_p, c_long)
    librpm.expandMacros.restype = c_int

    buf = ctypes.create_string_buffer(val, len(val) * 100)
    rc = librpm.expandMacros(None, None, buf, len(buf))
    if rc != 0:
        raise RuntimeError("failed to expand RPM macro %r" % (val,))
    return buf.value


# os.stat_result doesn't seem to be usable if you need to populate the fields
# after st_ctime, e.g. rdev 
Example #10
Source File: test_cftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_newSingleDigitDayOfMonth(self):
        """
        A file with a high-resolution timestamp which falls on a day of the
        month which can be represented by one decimal digit is formatted with
        one padding 0 to preserve the columns which come after it.
        """
        # A point about three months in the past, tweaked to fall on the first
        # of a month so we test the case we want to test.
        then = self.now - (60 * 60 * 24 * 31 * 3) + (60 * 60 * 24 * 4)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Sep 01 17:33 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Sep 02 09:33 foo') 
Example #11
Source File: test_cftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_localeIndependent(self):
        """
        The month name in the date is locale independent.
        """
        # A point about three months in the past.
        then = self.now - (60 * 60 * 24 * 31 * 3)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        # Fake that we're in a language where August is not Aug (e.g.: Spanish)
        currentLocale = locale.getlocale()
        locale.setlocale(locale.LC_ALL, "es_AR.UTF8")
        self.addCleanup(locale.setlocale, locale.LC_ALL, currentLocale)

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Aug 28 17:33 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Aug 29 09:33 foo')

    # If alternate locale is not available, the previous test will be
    # skipped, please install this locale for it to run 
Example #12
Source File: osfs.py    From pyfilesystem2 with MIT License 6 votes vote down vote up
def _make_access_from_stat(cls, stat_result):
        # type: (os.stat_result) -> Dict[Text, object]
        """Make an *access* info dict from an `os.stat_result` object.
        """
        access = {}  # type: Dict[Text, object]
        access["permissions"] = Permissions(mode=stat_result.st_mode).dump()
        access["gid"] = gid = stat_result.st_gid
        access["uid"] = uid = stat_result.st_uid
        if not _WINDOWS_PLATFORM:
            import grp
            import pwd

            try:
                access["group"] = grp.getgrgid(gid).gr_name
            except KeyError:  # pragma: no cover
                pass

            try:
                access["user"] = pwd.getpwuid(uid).pw_name
            except KeyError:  # pragma: no cover
                pass
        return access 
Example #13
Source File: osfs.py    From pyfilesystem2 with MIT License 6 votes vote down vote up
def _make_details_from_stat(cls, stat_result):
        # type: (os.stat_result) -> Dict[Text, object]
        """Make a *details* info dict from an `os.stat_result` object.
        """
        details = {
            "_write": ["accessed", "modified"],
            "accessed": stat_result.st_atime,
            "modified": stat_result.st_mtime,
            "size": stat_result.st_size,
            "type": int(cls._get_type_from_stat(stat_result)),
        }
        # On other Unix systems (such as FreeBSD), the following
        # attributes may be available (but may be only filled out if
        # root tries to use them):
        details["created"] = getattr(stat_result, "st_birthtime", None)
        ctime_key = "created" if _WINDOWS_PLATFORM else "metadata_changed"
        details[ctime_key] = stat_result.st_ctime
        return details 
Example #14
Source File: test_cftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_oldSingleDigitDayOfMonth(self):
        """
        A file with a high-resolution timestamp which falls on a day of the
        month which can be represented by one decimal digit is formatted with
        one padding 0 to preserve the columns which come after it.
        """
        # A point about 7 months in the past, tweaked to fall on the first of a
        # month so we test the case we want to test.
        then = self.now - (60 * 60 * 24 * 31 * 7) + (60 * 60 * 24 * 5)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 May 01  1973 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 May 02  1973 foo') 
Example #15
Source File: test_process.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def fstat(self, fd):
        """
        Fake C{os.fstat}.  Return a C{os.stat_result} filled with garbage.
        """
        return os.stat_result((0,) * 10) 
Example #16
Source File: osfs.py    From pyfilesystem2 with MIT License 5 votes vote down vote up
def _scandir(self, path, namespaces=None):
            # type: (Text, Optional[Collection[Text]]) -> Iterator[Info]
            self.check()
            namespaces = namespaces or ()
            _path = self.validatepath(path)
            sys_path = self.getsyspath(_path)
            with convert_os_errors("scandir", path, directory=True):
                for entry_name in os.listdir(sys_path):
                    _entry_name = fsdecode(entry_name)
                    entry_path = os.path.join(sys_path, _entry_name)
                    stat_result = os.stat(fsencode(entry_path))
                    info = {
                        "basic": {
                            "name": _entry_name,
                            "is_dir": stat.S_ISDIR(stat_result.st_mode),
                        }
                    }  # type: Dict[Text, Dict[Text, Any]]
                    if "details" in namespaces:
                        info["details"] = self._make_details_from_stat(stat_result)
                    if "stat" in namespaces:
                        info["stat"] = {
                            k: getattr(stat_result, k)
                            for k in dir(stat_result)
                            if k.startswith("st_")
                        }
                    if "lstat" in namespaces:
                        lstat_result = os.lstat(entry_path)
                        info["lstat"] = {
                            k: getattr(lstat_result, k)
                            for k in dir(lstat_result)
                            if k.startswith("st_")
                        }
                    if "link" in namespaces:
                        info["link"] = self._make_link_info(
                            os.path.join(sys_path, entry_name)
                        )
                    if "access" in namespaces:
                        info["access"] = self._make_access_from_stat(stat_result)

                    yield Info(info) 
Example #17
Source File: chroot.py    From cjworkbench with GNU Affero General Public License v3.0 5 votes vote down vote up
def _reown_output_file(self, path: Path, old_stat: os.stat_result) -> None:
        if not path.exists():
            # module deleted path
            raise ModuleExitedError(0, "Module bug: %r was deleted" % path)
        if path.is_symlink():
            # If the module wrote a symlink, DO NOT READ IT. That's a security
            # issue -- the module could write "/etc/passwd" and then we'd read it.
            raise ModuleExitedError(0, "SECURITY: module output a symlink")
        if not path.is_file():
            raise ModuleExitedError(0, "Module bug: output must be a regular file")

        os.chmod(path, old_stat.st_mode & 0o7777)
        os.chown(path, old_stat.st_uid, old_stat.st_gid) 
Example #18
Source File: osfs.py    From pyfilesystem2 with MIT License 5 votes vote down vote up
def _get_type_from_stat(cls, _stat):
        # type: (os.stat_result) -> ResourceType
        """Get the resource type from an `os.stat_result` object.
        """
        st_mode = _stat.st_mode
        st_type = stat.S_IFMT(st_mode)
        return cls.STAT_TO_RESOURCE_TYPE.get(st_type, ResourceType.unknown)

    # --------------------------------------------------------
    # Required Methods
    # -------------------------------------------------------- 
Example #19
Source File: test_cftp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_oldFile(self):
        """
        A file with an mtime six months (approximately) or more in the past has
        a listing including a low-resolution timestamp.
        """
        # Go with 7 months.  That's more than 6 months.
        then = self.now - (60 * 60 * 24 * 31 * 7)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Apr 26  1973 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Apr 27  1973 foo') 
Example #20
Source File: test_cftp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_newFile(self):
        """
        A file with an mtime fewer than six months (approximately) in the past
        has a listing including a high-resolution timestamp excluding the year.
        """
        # A point about three months in the past.
        then = self.now - (60 * 60 * 24 * 31 * 3)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Aug 28 17:33 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Aug 29 09:33 foo') 
Example #21
Source File: director.py    From Thespian with MIT License 5 votes vote down vote up
def zipstat(fname):
    s = realstat(fname)
    timefix = lambda t: (time.mktime((1980,1,1,0,0,0,0,0,0))
                         if time.localtime(s.st_mtime)[0] < 1980
                         else t)
    return os.stat_result((s[0], s[1], s[2], s[3], s[4], s[5], s[6],
                          timefix(s[7]), timefix(s[8]), timefix(s[9]))) 
Example #22
Source File: utils.py    From chalice with Apache License 2.0 5 votes vote down vote up
def stat(self, path):
        # type: (str)  -> os.stat_result
        return os.stat(path) 
Example #23
Source File: test_os.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_stat_result_pickle(self):
        result = os.stat(self.fname)
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            p = pickle.dumps(result, proto)
            self.assertIn(b'stat_result', p)
            if proto < 4:
                self.assertIn(b'cos\nstat_result\n', p)
            unpickled = pickle.loads(p)
            self.assertEqual(result, unpickled) 
Example #24
Source File: builder.py    From shiv with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _write_to_zipapp(
    arhive: zipfile.ZipFile,
    arcname: str,
    data_source: Union[Path, bytes],
    date_time: Tuple[int, int, int, int, int, int],
    compression: int,
    contents_hash: hashlib.sha3_256,
) -> None:
    """Write a file or a bytestring to a ZipFile as a separate entry and
    update contents_hash as a side effect

    The approach is borrowed from 'wheel' code.
    """
    if isinstance(data_source, Path):
        with data_source.open("rb") as f:
            data = f.read()
            st: Optional[os.stat_result] = os.fstat(f.fileno())
    else:
        data = data_source
        st = None

    contents_hash.update(data)

    zinfo = zipfile.ZipInfo(arcname, date_time=date_time)
    zinfo.compress_type = compression
    if st is not None:
        zinfo.external_attr = (stat.S_IMODE(st.st_mode) | stat.S_IFMT(st.st_mode)) << 16

    arhive.writestr(zinfo, data) 
Example #25
Source File: path.py    From tbot with GNU General Public License v3.0 5 votes vote down vote up
def stat(self) -> os.stat_result:
        """
        Return the result of ``stat`` on this path.

        Tries to imitate the results of :meth:`pathlib.Path.stat`, returns a
        :class:`os.stat_result`.
        """
        ec, stat_str = self.host.exec("stat", "-t", self)
        if ec != 0:
            raise OSError(errno.ENOENT, f"Can't stat {self}")

        stat_res = stat_str[len(self._local_str()) + 1 :].split(" ")

        return os.stat_result(
            (
                int(stat_res[2], 16),
                int(stat_res[6]),
                0,
                int(stat_res[7]),
                int(stat_res[3]),
                int(stat_res[4]),
                int(stat_res[0]),
                int(stat_res[10]),
                int(stat_res[11]),
                int(stat_res[12]),
            )
        ) 
Example #26
Source File: test_nt.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_waitpid(self):
        #sanity check
        ping_cmd = os.path.join(os.environ["windir"], "system32", "ping")
        pid = nt.spawnv(nt.P_NOWAIT, ping_cmd ,  ["ping", "-n", "1", "127.0.0.1"])

        new_pid, exit_stat = nt.waitpid(pid, 0)

        #negative cases
        self.assertRaisesMessage(OSError, "[Errno 10] No child processes", nt.waitpid, -1234, 0)

        self.assertRaises(TypeError, nt.waitpid, "", 0)

    # stat_result test 
Example #27
Source File: fuse.py    From tgcloud with Apache License 2.0 5 votes vote down vote up
def getattr_compat_0_1(self, *a):
        from os import stat_result

        return stat_result(self.getattr(*a)) 
Example #28
Source File: __init__.py    From hddfancontrol with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
    with unittest.mock.patch("hddfancontrol.os.stat") as os_stat_mock, \
            unittest.mock.patch("hddfancontrol.stat") as stat_mock, \
            unittest.mock.patch("hddfancontrol.subprocess.check_output") as subprocess_check_output_mock, \
            unittest.mock.patch("hddfancontrol.Drive.getPrettyName") as drive_getPrettyName:
      os_stat_mock.return_value = os.stat_result
      stat_mock.stat.S_IFBLK.return_value = True
      subprocess_check_output_mock.return_value = ""
      drive_getPrettyName.return_value = "drive_name"
      self.drive = hddfancontrol.Drive("/dev/sdz", None, 30, 50, False)
    self.hddtemp_daemon = None 
Example #29
Source File: rewrite.py    From pytest with MIT License 5 votes vote down vote up
def _write_pyc(
        state: "AssertionState",
        co: types.CodeType,
        source_stat: os.stat_result,
        pyc: Path,
    ) -> bool:
        proc_pyc = "{}.{}".format(pyc, os.getpid())
        try:
            fp = open(proc_pyc, "wb")
        except OSError as e:
            state.trace(
                "error writing pyc file at {}: errno={}".format(proc_pyc, e.errno)
            )
            return False

        try:
            _write_pyc_fp(fp, source_stat, co)
            os.rename(proc_pyc, fspath(pyc))
        except OSError as e:
            state.trace("error writing pyc file at {}: {}".format(pyc, e))
            # we ignore any failure to write the cache file
            # there are many reasons, permission-denied, pycache dir being a
            # file etc.
            return False
        finally:
            fp.close()
        return True 
Example #30
Source File: test_cftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_newFile(self):
        """
        A file with an mtime fewer than six months (approximately) in the past
        has a listing including a high-resolution timestamp excluding the year.
        """
        # A point about three months in the past.
        then = self.now - (60 * 60 * 24 * 31 * 3)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Aug 28 17:33 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Aug 29 09:33 foo')