diff --git a/common/lib/capa/capa/safe_exec.py b/common/lib/capa/capa/safe_exec.py index dd52c3571a..3d481495d4 100644 --- a/common/lib/capa/capa/safe_exec.py +++ b/common/lib/capa/capa/safe_exec.py @@ -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): diff --git a/common/lib/capa/capa/tests/test_safe_exec.py b/common/lib/capa/capa/tests/test_safe_exec.py index 8a65cb6c38..7ed44a69a1 100644 --- a/common/lib/capa/capa/tests/test_safe_exec.py +++ b/common/lib/capa/capa/tests/test_safe_exec.py @@ -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 = {}