test_errors.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import unittest
  2. import ray
  3. import ray.rllib.algorithms.impala as impala
  4. import ray.rllib.algorithms.pg as pg
  5. from ray.rllib.utils.error import EnvError
  6. from ray.rllib.utils.test_utils import framework_iterator
  7. class TestErrors(unittest.TestCase):
  8. """Tests various failure-modes, making sure we produce meaningful errmsgs."""
  9. @classmethod
  10. def setUpClass(cls) -> None:
  11. ray.init()
  12. @classmethod
  13. def tearDownClass(cls) -> None:
  14. ray.shutdown()
  15. def test_no_gpus_error(self):
  16. """Tests errors related to no-GPU/too-few GPUs/etc.
  17. This test will only work ok on a CPU-only machine.
  18. """
  19. config = impala.ImpalaConfig().environment("CartPole-v1")
  20. for _ in framework_iterator(config):
  21. self.assertRaisesRegex(
  22. RuntimeError,
  23. # (?s): "dot matches all" (also newlines).
  24. "(?s)Found 0 GPUs on your machine.+To change the config",
  25. lambda: config.build(),
  26. )
  27. def test_bad_envs(self):
  28. """Tests different "bad env" errors."""
  29. config = (
  30. pg.PGConfig().rollouts(num_rollout_workers=0)
  31. # Non existing/non-registered gym env string.
  32. .environment("Alien-Attack-v42")
  33. )
  34. for _ in framework_iterator(config):
  35. self.assertRaisesRegex(
  36. EnvError,
  37. f"The env string you provided \\('{config.env}'\\) is",
  38. lambda: config.build(),
  39. )
  40. # Malformed gym env string (must have v\d at end).
  41. config.environment("Alien-Attack-part-42")
  42. for _ in framework_iterator(config):
  43. self.assertRaisesRegex(
  44. EnvError,
  45. f"The env string you provided \\('{config.env}'\\) is",
  46. lambda: config.build(),
  47. )
  48. # Non-existing class in a full-class-path.
  49. config.environment("ray.rllib.examples.env.random_env.RandomEnvThatDoesntExist")
  50. for _ in framework_iterator(config):
  51. self.assertRaisesRegex(
  52. EnvError,
  53. f"The env string you provided \\('{config.env}'\\) is",
  54. lambda: config.build(),
  55. )
  56. # Non-existing module inside a full-class-path.
  57. config.environment("ray.rllib.examples.env.module_that_doesnt_exist.SomeEnv")
  58. for _ in framework_iterator(config):
  59. self.assertRaisesRegex(
  60. EnvError,
  61. f"The env string you provided \\('{config.env}'\\) is",
  62. lambda: config.build(),
  63. )
  64. if __name__ == "__main__":
  65. import pytest
  66. import sys
  67. sys.exit(pytest.main(["-v", __file__]))