Skip to content

Commit d05a3bf

Browse files
cmaloneyclaude
andcommitted
gh-71199: Test the platform module and loading os pickles through it
posix (nt on Windows) is a builtin importable only on its own platform, and pickles name posixmodule types and functions either through os or through that module. Both spellings must keep loading. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3945eaf commit d05a3bf

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

‎Lib/test/test_os/test_os.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import decimal
99
import errno
1010
import fractions
11+
import importlib.util
1112
import itertools
1213
import locale
1314
import os
@@ -188,6 +189,36 @@ def fqdn(obj):
188189
if hasattr(os, "waitid_result"):
189190
self.assertEqual(fqdn(os.waitid_result), (native, "waitid_result"))
190191

192+
def test_platform_module(self):
193+
# posix and nt stay builtins, importable only on their own platform.
194+
other = 'posix' if os.name == 'nt' else 'nt'
195+
self.assertIs(importlib.import_module(os.name).stat, os.stat)
196+
self.assertIn(os.name, sys.builtin_module_names)
197+
self.assertNotIn(other, sys.builtin_module_names)
198+
with self.assertRaises(ImportError):
199+
importlib.import_module(other)
200+
201+
def test_platform_module_from_spec(self):
202+
# Loading by hand (as LazyLoader does) must give a working module.
203+
spec = importlib.util.find_spec(os.name)
204+
mod = importlib.util.module_from_spec(spec)
205+
spec.loader.exec_module(mod)
206+
self.assertEqual(mod.getpid(), os.getpid())
207+
self.assertIs(sys.modules[os.name].stat, os.stat)
208+
209+
def test_pickle_global_names(self):
210+
# Pickles reference these via the platform module (posix or nt) or
211+
# via os; both must keep loading.
212+
names = ['stat', 'stat_result', 'times', 'times_result', 'DirEntry']
213+
names += [name for name in ('statvfs_result', 'uname_result',
214+
'sched_param', 'waitid_result')
215+
if hasattr(os, name)]
216+
for module in ('os', os.name):
217+
for name in names:
218+
with self.subTest(module=module, name=name):
219+
p = f'c{module}\n{name}\n.'.encode()
220+
self.assertIs(pickle.loads(p), getattr(os, name))
221+
191222

192223
# Tests creating TESTFN
193224
class FileTests(unittest.TestCase):
@@ -5577,6 +5608,15 @@ def test_times(self):
55775608
self.assertEqual(times.children_system, 0)
55785609
self.assertEqual(times.elapsed, 0)
55795610

5611+
def test_times_result_pickle(self):
5612+
result = os.times()
5613+
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
5614+
with self.subTest(f'protocol {proto}'):
5615+
p = pickle.dumps(result, proto)
5616+
self.assertIn(b'times_result', p)
5617+
unpickled = pickle.loads(p)
5618+
self.assertEqual(result, unpickled)
5619+
55805620

55815621
@support.requires_fork()
55825622
class ForkTests(unittest.TestCase):

0 commit comments

Comments
 (0)