Skip to content

Commit

Permalink
Cleanup and fixed for Python3 update
Browse files Browse the repository at this point in the history
  • Loading branch information
loechel committed Jan 29, 2016
1 parent c5479bd commit d5c2bdd
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 22 deletions.
9 changes: 6 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
from setuptools import find_packages, setup

here = os.path.abspath(os.path.dirname(__file__))


def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

Expand All @@ -34,7 +36,7 @@ def read(*rnames):
read('README.rst')
+ '\n\n' +
read('CHANGES.rst')
),
),
keywords = "zope untrusted python",
classifiers = [
'Development Status :: 5 - Production/Stable',
Expand All @@ -49,7 +51,8 @@ def read(*rnames):
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP',
'Framework :: Zope3'],
'Framework :: Zope3',
],
url='http://github.com/zopefoundation/zope.untrustedpython',
license='ZPL 2.1',
packages=find_packages('src'),
Expand All @@ -59,7 +62,7 @@ def read(*rnames):
'setuptools',
'RestrictedPython',
'zope.security',
],
],
test_suite = 'zope.untrustedpython.tests.test_suite',
include_package_data = True,
zip_safe = True,
Expand Down
13 changes: 8 additions & 5 deletions src/zope/untrustedpython/builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
"""Protection of builtin objects.
"""
from zope.security.proxy import ProxyFactory

import new


def SafeBuiltins():

builtins = {}
Expand Down Expand Up @@ -60,8 +62,8 @@ def SafeBuiltins():
# check in merge_class_dict in object.c. The assert macro
# seems to be doing the wrong think. Basically, if an object
# has bases, then bases is assumed to be a tuple.
#dir,
]:
# dir,
]:

try:
value = getattr(__builtin__, name)
Expand All @@ -77,11 +79,11 @@ def SafeBuiltins():
from sys import modules

def _imp(name, fromlist, prefix=''):
module = modules.get(prefix+name)
module = modules.get(prefix + name)
if module is not None:
if fromlist or ('.' not in name):
return module
return modules[prefix+name.split('.')[0]]
return modules[prefix + name.split('.')[0]]

def __import__(name, globals=None, locals=None, fromlist=()):
# Waaa, we have to emulate __import__'s weird semantics.
Expand All @@ -95,7 +97,7 @@ def __import__(name, globals=None, locals=None, fromlist=()):
# so remove last name segment:
__name__ = '.'.join(__name__.split('.')[:-1])
if __name__:
module = _imp(name, fromlist, __name__+'.')
module = _imp(name, fromlist, __name__ + '.')
if module is not None:
return module

Expand All @@ -109,6 +111,7 @@ def __import__(name, globals=None, locals=None, fromlist=()):

return builtins


class ImmutableModule(new.module):
def __init__(self, name='__builtins__', **kw):
new.module.__init__(self, name)
Expand Down
9 changes: 6 additions & 3 deletions src/zope/untrustedpython/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@
from zope.untrustedpython.builtins import SafeBuiltins
from zope.untrustedpython.rcompile import compile


def exec_code(code, globals, locals=None):
globals['__builtins__'] = SafeBuiltins
exec code in globals, locals
exec(code, globals, locals)


def exec_src(source, globals, locals=None):
globals['__builtins__'] = SafeBuiltins
code = compile(source, '<string>', 'exec')
exec code in globals, locals
exec(code, globals, locals)


class CompiledExpression(object):
Expand All @@ -43,6 +45,7 @@ def eval(self, globals, locals=None):
else:
return eval(self.code, globals, locals)


class CompiledProgram(object):
"""A compiled expression
"""
Expand All @@ -55,4 +58,4 @@ def exec_(self, globals, locals=None, output=None):
globals['__builtins__'] = SafeBuiltins
if output is not None:
globals['untrusted_output'] = output
exec self.code in globals, locals
exec(self.code, globals, locals)
13 changes: 7 additions & 6 deletions src/zope/untrustedpython/rcompile.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,20 @@
import RestrictedPython.RCompile
from RestrictedPython.SelectCompiler import ast

def compile(text, filename, mode):
if not isinstance(text, basestring):

def compile(source, filename, mode):
if not isinstance(source, basestring):
raise TypeError("Compiled source must be string")
gen = RExpression(text, str(filename), mode)
gen = RExpression(source, str(filename), mode)
gen.compile()
return gen.getCode()


class RExpression(RestrictedPython.RCompile.RestrictedCompileMode):

CodeGeneratorClass = compiler.pycodegen.ExpressionCodeGenerator

def __init__(self, source, filename, mode = "eval"):
def __init__(self, source, filename, mode="eval"):
self.mode = mode
RestrictedPython.RCompile.RestrictedCompileMode.__init__(
self, source, filename)
Expand Down Expand Up @@ -86,10 +88,9 @@ def visitPrint(self, node, walker):
node.dest = ast.Name('untrusted_output')
return node
visitPrintnl = visitPrint

def visitRaise(self, node, walker):
self.error(node, "raise statements are not supported")

def visitTryExcept(self, node, walker):
self.error(node, "try/except statements are not supported")

13 changes: 8 additions & 5 deletions src/zope/untrustedpython/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,19 @@
##############################################################################
"""Tests for zope.security.checker
"""
import unittest
from zope.untrustedpython import interpreter, rcompile

from zope.untrustedpython import interpreter
from zope.untrustedpython import rcompile
from zope.untrustedpython.builtins import SafeBuiltins

import unittest


class Test_SafeBuiltins(unittest.TestCase):

def test_simple(self):
d = {'__builtins__': SafeBuiltins}
exec 'x = str(1)' in d
exec('x = str(1)', d)
self.assertEqual(d['x'], '1')

def test_immutable(self):
Expand Down Expand Up @@ -149,12 +152,12 @@ def test_CompiledCode_explicit_writable(self):
f = StringIO.StringIO()
code = rcompile.compile(
"print >> f, 'hi',\nprint >> f, 'world'", '', 'exec')
exec code in {'f': f}
exec(code, {'f': f})
self.assertEqual(f.getvalue(), 'hi world\n')

def test_CompiledCode_default_output(self):
def _exec(code, locals):
exec code in locals
exec(code, locals)
code = rcompile.compile("print 'hi',\nprint 'world'", '', 'exec')
self.assertRaises(NameError, _exec, code, {})
import StringIO
Expand Down

0 comments on commit d5c2bdd

Please sign in to comment.