Skip to content

Commit c2b397e

Browse files
akxtomasr8
andauthored
Strip extra leading slashes in /etc/localtime (#1165)
* Strip extra leading slashes in `/etc/localtime` Fixes #990 Co-authored-by: Tomas R. <[email protected]>
1 parent 6fe076a commit c2b397e

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

babel/localtime/_unix.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,13 @@ def _get_localzone(_root: str = '/') -> datetime.tzinfo:
4545
else:
4646
pos = link_dst.find('/zoneinfo/')
4747
if pos >= 0:
48-
zone_name = link_dst[pos + 10:]
48+
# On occasion, the `/etc/localtime` symlink has a double slash, e.g.
49+
# "/usr/share/zoneinfo//UTC", which would make `zoneinfo.ZoneInfo`
50+
# complain (no absolute paths allowed), and we'd end up returning
51+
# `None` (as a fix for #1092).
52+
# Instead, let's just "fix" the double slash symlink by stripping
53+
# leading slashes before passing the assumed zone name forward.
54+
zone_name = link_dst[pos + 10:].lstrip("/")
4955
tzinfo = _get_tzinfo(zone_name)
5056
if tzinfo is not None:
5157
return tzinfo

tests/test_localtime.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import os
12
import sys
3+
from unittest.mock import Mock
24

35
import pytest
46

@@ -27,3 +29,16 @@ def test_issue_1092_with_pytz(monkeypatch):
2729
monkeypatch.setenv("TZ", "/UTC") # Malformed timezone name.
2830
with pytest.raises(LookupError):
2931
get_localzone()
32+
33+
34+
@pytest.mark.skipif(
35+
sys.platform == "win32",
36+
reason="Issue 990 is not applicable on Windows",
37+
)
38+
def test_issue_990(monkeypatch):
39+
monkeypatch.setenv("TZ", "")
40+
fake_readlink = Mock(return_value="/usr/share/zoneinfo////UTC") # Double slash, oops!
41+
monkeypatch.setattr(os, "readlink", fake_readlink)
42+
from babel.localtime._unix import _get_localzone
43+
assert _get_localzone() is not None
44+
fake_readlink.assert_called_with("/etc/localtime")

0 commit comments

Comments
 (0)