[3.9] gh-136065: Fix quadratic complexity in os.path.expandvars() (GH-134952) (GH-140839)

(cherry picked from commit f029e8db62)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
This commit is contained in:
Łukasz Langa 2025-10-31 17:05:53 +01:00 committed by GitHub
parent 798eaca665
commit 2e6150adcc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 96 additions and 116 deletions

View file

@ -9,7 +9,7 @@
import warnings
from test import support
from test.support.script_helper import assert_python_ok
from test.support import FakePath
from test.support import FakePath, EnvironmentVarGuard
def create_file(filename, data=b'foo'):
@ -374,7 +374,7 @@ def test_splitdrive(self):
def test_expandvars(self):
expandvars = self.pathmodule.expandvars
with support.EnvironmentVarGuard() as env:
with EnvironmentVarGuard() as env:
env.clear()
env["foo"] = "bar"
env["{foo"] = "baz1"
@ -408,7 +408,7 @@ def test_expandvars_nonascii(self):
expandvars = self.pathmodule.expandvars
def check(value, expected):
self.assertEqual(expandvars(value), expected)
with support.EnvironmentVarGuard() as env:
with EnvironmentVarGuard() as env:
env.clear()
nonascii = support.FS_NONASCII
env['spam'] = nonascii
@ -429,6 +429,19 @@ def check(value, expected):
os.fsencode('$bar%s bar' % nonascii))
check(b'$spam}bar', os.fsencode('%s}bar' % nonascii))
@support.requires_resource('cpu')
def test_expandvars_large(self):
expandvars = self.pathmodule.expandvars
with EnvironmentVarGuard() as env:
env.clear()
env["A"] = "B"
n = 100_000
self.assertEqual(expandvars('$A'*n), 'B'*n)
self.assertEqual(expandvars('${A}'*n), 'B'*n)
self.assertEqual(expandvars('$A!'*n), 'B!'*n)
self.assertEqual(expandvars('${A}A'*n), 'BA'*n)
self.assertEqual(expandvars('${'*10*n), '${'*10*n)
def test_abspath(self):
self.assertIn("foo", self.pathmodule.abspath("foo"))
with warnings.catch_warnings():