Jailed code importing random explicitly would get the wrong seed.

This commit is contained in:
Ned Batchelder
2013-02-27 14:13:45 -05:00
parent f3e8d5bb7a
commit 283fc47a95
2 changed files with 14 additions and 0 deletions

View File

@@ -9,9 +9,11 @@ CODE_PROLOG = """\
from __future__ import division
import random as random_module
import sys
random = random_module.Random(%r)
random.Random = random_module.Random
del random_module
sys.modules['random'] = random
"""
def safe_exec(code, globals_dict, random_seed=None, python_path=None):

View File

@@ -37,6 +37,18 @@ class TestSafeExec(unittest.TestCase):
safe_exec("rnums = [random.randint(0, 999) for _ in xrange(100)]", g, random_seed=17)
self.assertEqual(g['rnums'], rnums)
def test_random_is_still_importable(self):
g = {}
r = random.Random(17)
rnums = [r.randint(0, 999) for _ in xrange(100)]
# With a seed, the results are predictable even from the random module
safe_exec(
"import random\n"
"rnums = [random.randint(0, 999) for _ in xrange(100)]\n",
g, random_seed=17)
self.assertEqual(g['rnums'], rnums)
def test_python_lib(self):
pylib = os.path.dirname(__file__) + "/test_files/pylib"
g = {}