Refactor testing.random
@@ -8,29 +8,13 @@ import unittest
import cupy
-# In some tests (which utilize condition.repeat or condition.retry),
-# setUp/tearDown is nested. _setup_random() and _teardown_random() do their
-# work only in the outermost setUp/tearDown pair.
-_nest_count = 0
-
_old_numpy_random_state = None
_old_cupy_random_states = None
-@atexit.register
-def _check_teardown():
- assert _nest_count == 0, ('_setup_random() and _teardown_random() '
- 'must be called in pairs.')
-
-
-def _setup_random():
- """Sets up the deterministic random states of ``numpy`` and ``cupy``.
-
- """
- global _nest_count
+def do_setup(deterministic=True):
global _old_numpy_random_state
global _old_cupy_random_states
- if _nest_count == 0:
_old_numpy_random_state = numpy.random.get_state()
_old_cupy_random_states = cupy.random.generator._random_states
cupy.random.reset_states()
@@ -40,14 +24,44 @@ def _setup_random():
assert (cupy.random.generator._random_states is not
_old_cupy_random_states)
- nondeterministic = bool(int(os.environ.get(
- 'CUPY_TEST_RANDOM_NONDETERMINISTIC', '0')))
- if nondeterministic:
+ if not deterministic:
numpy.random.seed()
cupy.random.seed()
else:
numpy.random.seed(100)
cupy.random.seed(101)
+
+
+def do_teardown():
+ global _old_numpy_random_state
+ global _old_cupy_random_states
+ numpy.random.set_state(_old_numpy_random_state)
+ cupy.random.generator._random_states = _old_cupy_random_states
+ _old_numpy_random_state = None
+ _old_cupy_random_states = None
+
+
+# In some tests (which utilize condition.repeat or condition.retry),
+# setUp/tearDown is nested. _setup_random() and _teardown_random() do their
+# work only in the outermost setUp/tearDown pair.
+_nest_count = 0
+
+
+@atexit.register
+def _check_teardown():
+ assert _nest_count == 0, ('_setup_random() and _teardown_random() '
+ 'must be called in pairs.')
+
+
+def _setup_random():
+ """Sets up the deterministic random states of ``numpy`` and ``cupy``.
+
+ """
+ global _nest_count
+ if _nest_count == 0:
+ nondeterministic = bool(int(os.environ.get(
+ 'CUPY_TEST_RANDOM_NONDETERMINISTIC', '0')))
+ do_setup(not nondeterministic)
_nest_count += 1
@@ -56,15 +70,10 @@ def _teardown_random():
"""
global _nest_count
- global _old_numpy_random_state
- global _old_cupy_random_states
assert _nest_count > 0, '_setup_random has not been called'
_nest_count -= 1
if _nest_count == 0:
- numpy.random.set_state(_old_numpy_random_state)
- cupy.random.generator._random_states = _old_cupy_random_states
- _old_numpy_random_state = None
- _old_cupy_random_states = None
+ do_teardown()
def generate_seed():
