Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-94808: Cover LOAD_GLOBAL for custom dict subtypes #96767

Merged
merged 3 commits into from
Nov 4, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Lib/test/test_builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,7 @@ def test_exec_globals(self):
self.assertRaises(TypeError,
exec, code, {'__builtins__': 123})

def test_exec_globals_frozen(self):
class frozendict_error(Exception):
pass

Expand Down Expand Up @@ -768,6 +769,36 @@ def __setitem__(self, key, value):
self.assertRaises(frozendict_error,
exec, code, namespace)

def test_exec_globals_error_on_get(self):
# custom `globals` or `builtins` can raise errors on item access
class setonlyerror(Exception):
pass

class setonlydict(dict):
def __getitem__(self, key):
raise setonlyerror

# globals' `__getitem__` raises
code = compile("globalname", "test", "exec")
self.assertRaises(setonlyerror,
exec, code, setonlydict({'globalname': 1}))

# builtins' `__getitem__` raises
code = compile("superglobal", "test", "exec")
self.assertRaises(setonlyerror, exec, code,
{'__builtins__': setonlydict({'superglobal': 1})})

def test_exec_globals_dict_subclass(self):
class customdict(dict): # this one should not do anything fancy
pass

code = compile("superglobal", "test", "exec")
# works correctly
exec(code, {'__builtins__': customdict({'superglobal': 1})})
# custom builtins dict subclass is missing key
self.assertRaisesRegex(NameError, "name 'superglobal' is not defined",
exec, code, {'__builtins__': customdict()})

def test_exec_redirected(self):
savestdout = sys.stdout
sys.stdout = None # Whatever that cannot flush()
Expand Down