Skip to content
This repository has been archived by the owner on Aug 30, 2019. It is now read-only.

Commit

Permalink
test_closure() uses .execute() instead of .call()
Browse files Browse the repository at this point in the history
  • Loading branch information
vstinner committed Jan 22, 2013
1 parent d4c7154 commit ce278b4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 29 deletions.
5 changes: 5 additions & 0 deletions sandbox/test/__init__.py
Expand Up @@ -45,3 +45,8 @@ def wrapper(*args, **kw):
return wrapper
return decorator

def execute_code(code):
code_obj = compile(code, "<test>", "exec")
namespace = {}
exec code_obj in namespace, namespace

59 changes: 30 additions & 29 deletions sandbox/test/test_attributes.py
@@ -1,5 +1,5 @@
from sandbox import HAVE_PYPY, SandboxError
from sandbox.test import createSandbox, SkipTest
from sandbox.test import createSandbox, SkipTest, execute_code

# FIXME: reenable these tests
if HAVE_PYPY:
Expand All @@ -18,38 +18,39 @@ def mysum(a, b):
return func_globals['SECRET']

def test_closure():
def read_closure_secret():
def createClosure(secret):
def closure():
return secret
return closure
func = createClosure(42)
try:
cell = func.func_closure[0]
except AttributeError:
# Python 2.6+
cell = func.__closure__[0]
# Does Python < 2.5 have the cell_contents attribute? See this recipe,
# get_cell_value(), for version without the attribute:
# http://code.activestate.com/recipes/439096/
secret = cell.cell_contents
assert secret == 42

def check_closure():
try:
read_closure_secret()
except AttributeError, err:
assert str(err) == "'function' object has no attribute '__closure__'"
else:
assert False, "func_closure is present"
code = '''
def read_closure_secret():
def createClosure(secret):
def closure():
return secret
return closure
func = createClosure(42)
try:
cell = func.func_closure[0]
except AttributeError:
# Python 2.6+
cell = func.__closure__[0]
# Does Python < 2.5 have the cell_contents attribute? See this recipe,
# get_cell_value(), for version without the attribute:
# http://code.activestate.com/recipes/439096/
secret = cell.cell_contents
assert secret == 42
'''

sandbox_code = code + '''
try:
read_closure_secret()
except AttributeError, err:
assert str(err) == "'function' object has no attribute '__closure__'"
else:
assert False, "func_closure is present"
'''

# Begin by a test outside the sandbox to fill the type cache
read_closure_secret()
createSandbox().call(check_closure)
createSandbox().execute(sandbox_code)

# Repeat the test to ensure that the attribute cache is cleared correctly
read_closure_secret()
createSandbox().call(check_closure)
execute_code(code)

def test_func_globals():
def func_globals_denied():
Expand Down

0 comments on commit ce278b4

Please sign in to comment.