forked from pytorch/rl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_utils.py
381 lines (302 loc) · 11.4 KB
/
test_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import os
import sys
from copy import copy
from importlib import import_module
from unittest import mock
import _utils_internal
import pytest
import torch
from _utils_internal import get_default_devices
from torchrl._utils import _rng_decorator, get_binary_env_var, implement_for
from torchrl.envs.libs.gym import gym_backend, GymWrapper, set_gym_backend
@pytest.mark.parametrize("value", ["True", "1", "true"])
def test_get_binary_env_var_positive(value):
try:
key = "SOME_ENVIRONMENT_VARIABLE_UNLIKELY_TO_BE_IN_ENVIRONMENT"
assert key not in os.environ
os.environ[key] = value
assert get_binary_env_var(key)
finally:
if key in os.environ:
del os.environ[key]
@pytest.mark.parametrize("value", ["False", "0", "false"])
def test_get_binary_env_var_negative(value):
try:
key = "SOME_ENVIRONMENT_VARIABLE_UNLIKELY_TO_BE_IN_ENVIRONMENT"
assert key not in os.environ
os.environ[key] = "True"
assert get_binary_env_var(key)
os.environ[key] = value
assert not get_binary_env_var(key)
finally:
if key in os.environ:
del os.environ[key]
def test_get_binary_env_var_missing():
try:
key = "SOME_ENVIRONMENT_VARIABLE_UNLIKELY_TO_BE_IN_ENVIRONMENT"
assert key not in os.environ
assert not get_binary_env_var(key)
finally:
if key in os.environ:
del os.environ[key]
def test_get_binary_env_var_wrong_value():
try:
key = "SOME_ENVIRONMENT_VARIABLE_UNLIKELY_TO_BE_IN_ENVIRONMENT"
assert key not in os.environ
os.environ[key] = "smthwrong"
with pytest.raises(ValueError):
get_binary_env_var(key)
finally:
if key in os.environ:
del os.environ[key]
def uncallable(f):
class UncallableObject:
def __init__(self, other):
for k, v in other.__dict__.items():
if k not in ("__call__", "__dict__", "__weakref__"):
setattr(self, k, v)
g = UncallableObject(f)
return g
class implement_for_test_functions:
"""
Groups functions that are used in tests for `implement_for` decorator.
"""
@staticmethod
@implement_for(lambda: import_module("_utils_internal"), "0.3")
def select_correct_version():
"""To test from+ range and that this function is not selected as the implementation."""
return "0.3+V1"
@staticmethod
@implement_for("_utils_internal", "0.3")
def select_correct_version(): # noqa: F811
"""To test that this function is selected as the implementation (last implementation)."""
return "0.3+"
@staticmethod
@implement_for(lambda: import_module("_utils_internal"), "0.2", "0.3")
def select_correct_version(): # noqa: F811
"""To test that right bound is not included."""
return "0.2-0.3"
@staticmethod
@implement_for("_utils_internal", "0.1", "0.2")
def select_correct_version(): # noqa: F811
"""To test that function with missing from-to range is ignored."""
return "0.1-0.2"
@staticmethod
@implement_for("missing_module")
def missing_module():
"""To test that calling decorated function with missing module raises an exception."""
return "missing"
@staticmethod
@implement_for("_utils_internal", None, "0.3")
def missing_version():
return "0-0.3"
@staticmethod
@implement_for("_utils_internal", "0.4")
def missing_version(): # noqa: F811
return "0.4+"
def test_implement_for():
assert implement_for_test_functions.select_correct_version() == "0.3+"
def test_implement_for_missing_module():
msg = r"Supported version of 'test_utils.implement_for_test_functions.missing_module' has not been found."
with pytest.raises(ModuleNotFoundError, match=msg):
implement_for_test_functions.missing_module()
def test_implement_for_missing_version():
msg = r"Supported version of 'test_utils.implement_for_test_functions.missing_version' has not been found."
with pytest.raises(ModuleNotFoundError, match=msg):
implement_for_test_functions.missing_version()
def test_implement_for_reset():
assert implement_for_test_functions.select_correct_version() == "0.3+"
_impl = copy(implement_for._implementations)
name = implement_for.get_func_name(
implement_for_test_functions.select_correct_version
)
for setter in implement_for._setters:
if implement_for.get_func_name(setter.fn) == name and setter.fn() != "0.3+":
setter.module_set()
assert implement_for_test_functions.select_correct_version() != "0.3+"
implement_for.reset(_impl)
assert implement_for_test_functions.select_correct_version() == "0.3+"
@pytest.mark.parametrize(
"version, from_version, to_version, expected_check",
[
("0.21.0", "0.21.0", None, True),
("0.21.0", None, "0.21.0", False),
("0.9.0", "0.11.0", "0.21.0", False),
("0.9.0", "0.1.0", "0.21.0", True),
("0.19.99", "0.19.9", "0.21.0", True),
("0.19.99", None, "0.19.0", False),
("5.61.77", "0.21.0", None, True),
("5.61.77", None, "0.21.0", False),
],
)
def test_implement_for_check_versions(
version, from_version, to_version, expected_check
):
assert (
implement_for.check_version(version, from_version, to_version) == expected_check
)
@pytest.mark.parametrize(
"gymnasium_version, expected_from_version_gymnasium, expected_to_version_gymnasium",
[
("0.27.0", None, None),
("0.27.2", None, None),
("5.1.77", None, None),
],
)
@pytest.mark.parametrize(
"gym_version, expected_from_version_gym, expected_to_version_gym",
[
("0.21.0", "0.21.0", None),
("0.22.0", "0.21.0", None),
("5.61.77", "0.21.0", None),
("0.9.0", None, "0.21.0"),
("0.20.0", None, "0.21.0"),
("0.19.99", None, "0.21.0"),
],
)
def test_set_gym_environments(
gym_version,
expected_from_version_gym,
expected_to_version_gym,
gymnasium_version,
expected_from_version_gymnasium,
expected_to_version_gymnasium,
):
# mock gym and gymnasium imports
mock_gym = uncallable(mock.MagicMock())
mock_gym.__version__ = gym_version
mock_gym.__name__ = "gym"
sys.modules["gym"] = mock_gym
mock_gymnasium = uncallable(mock.MagicMock())
mock_gymnasium.__version__ = gymnasium_version
mock_gymnasium.__name__ = "gymnasium"
sys.modules["gymnasium"] = mock_gymnasium
import gym
import gymnasium
# look for the right function that should be called according to gym versions (and same for gymnasium)
for impfor in implement_for._setters:
if impfor.fn.__name__ == "_set_gym_environments":
if (impfor.module_name, impfor.from_version, impfor.to_version) == (
"gym",
expected_from_version_gym,
expected_to_version_gym,
):
expected_fn_gym = impfor.fn
elif (impfor.module_name, impfor.from_version, impfor.to_version) == (
"gymnasium",
expected_from_version_gymnasium,
expected_to_version_gymnasium,
):
expected_fn_gymnasium = impfor.fn
with set_gym_backend(gymnasium):
assert (
_utils_internal._set_gym_environments == expected_fn_gymnasium
), expected_fn_gym
with set_gym_backend(gym):
assert (
_utils_internal._set_gym_environments == expected_fn_gym
), expected_fn_gymnasium
with set_gym_backend(gymnasium):
assert (
_utils_internal._set_gym_environments == expected_fn_gymnasium
), expected_fn_gym
def test_set_gym_environments_no_version_gymnasium_found():
gymnasium_version = "0.26.0"
gymnasium_name = "gymnasium"
mock_gymnasium = uncallable(mock.MagicMock())
mock_gymnasium.__version__ = gymnasium_version
mock_gymnasium.__name__ = gymnasium_name
sys.modules["gymnasium"] = mock_gymnasium
import gymnasium
assert gymnasium.__version__ == "0.26.0"
# this version of gymnasium does not exist in implement_for
# therefore, set_gym_backend will not set anything and raise an ImportError.
msg = f"could not set anything related to gym backend {gymnasium_name} with version={gymnasium_version}."
with pytest.raises(ImportError, match=msg):
with set_gym_backend(gymnasium):
_utils_internal._set_gym_environments()
def test_set_gym_backend_types():
mock_gym = uncallable(mock.MagicMock())
gym_version = "0.26.0"
mock_gym.__version__ = gym_version
mock_gym.__name__ = "gym"
sys.modules["gym"] = mock_gym
import gym
assert not callable(gym)
with set_gym_backend("gym"):
assert gym_backend() == gym
with set_gym_backend(lambda: gym):
assert gym_backend() == gym
with set_gym_backend(gym):
assert gym_backend() == gym
# we check that the order where these funs are defined won't affect which is called
@implement_for("torch", "1.0", "1.8")
def torch_foo():
return 0
@implement_for("torch", "1.8", None)
def torch_foo(): # noqa: F811
return 1
@implement_for("torch", None, "1.0")
def torch_foo(): # noqa: F811
return 1
def test_set_gym_nested():
mock_gym = uncallable(mock.MagicMock())
mock_gym.__version__ = "0.21.0"
mock_gym.__name__ = "gym"
sys.modules["gym"] = mock_gym
mock_gymnasium = uncallable(mock.MagicMock())
mock_gymnasium.__version__ = "0.28.0"
mock_gymnasium.__name__ = "gymnasium"
sys.modules["gymnasium"] = mock_gymnasium
import gym
import gymnasium
assert torch_foo() == 1
class MockGym:
_is_batched = False
with set_gym_backend(gym):
GymWrapper._output_transform(
MockGym, (1, 2, True, {})
) # would break with gymnasium
assert torch_foo() == 1
with set_gym_backend(gymnasium):
GymWrapper._output_transform(
MockGym, (1, 2, True, True, {})
) # would break with gym
assert torch_foo() == 1
GymWrapper._output_transform(
MockGym, (1, 2, True, {})
) # would break with gymnasium
with set_gym_backend("gym"):
GymWrapper._output_transform(
MockGym, (1, 2, True, {})
) # would break with gymnasium
assert torch_foo() == 1
with set_gym_backend("gymnasium"):
GymWrapper._output_transform(
MockGym, (1, 2, True, True, {})
) # would break with gym
assert torch_foo() == 1
GymWrapper._output_transform(
MockGym, (1, 2, True, {})
) # would break with gymnasium
@pytest.mark.parametrize("device", get_default_devices())
def test_rng_decorator(device):
with torch.device(device):
torch.manual_seed(10)
s0a = torch.randn(3)
with _rng_decorator(0):
torch.randn(3)
s0b = torch.randn(3)
torch.manual_seed(10)
s1a = torch.randn(3)
s1b = torch.randn(3)
torch.testing.assert_close(s0a, s1a)
torch.testing.assert_close(s0b, s1b)
if __name__ == "__main__":
args, unknown = argparse.ArgumentParser().parse_known_args()
pytest.main([__file__, "--capture", "no", "--exitfirst"] + unknown)