run_tests.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env python3
  2. import random
  3. import gym
  4. import numpy as np
  5. from gym_minigrid.register import envList
  6. from gym_minigrid.minigrid import Grid
  7. # Test specifically importing a specific environment
  8. from gym_minigrid.envs import DoorKeyEnv
  9. # Test importing wrappers
  10. from gym_minigrid.wrappers import *
  11. ##############################################################################
  12. print('%d environments registered' % len(envList))
  13. for envName in envList:
  14. print('testing "%s"' % envName)
  15. # Load the gym environment
  16. env = gym.make(envName)
  17. env.reset()
  18. env.render('rgb_array')
  19. # Verify that the same seed always produces the same environment
  20. for i in range(0, 5):
  21. seed = 1337 + i
  22. env.seed(seed)
  23. grid1 = env.grid.encode()
  24. env.seed(seed)
  25. grid2 = env.grid.encode()
  26. assert np.array_equal(grid2, grid1)
  27. env.reset()
  28. # Run for a few episodes
  29. for i in range(5 * env.maxSteps):
  30. # Pick a random action
  31. action = random.randint(0, env.action_space.n - 1)
  32. obs, reward, done, info = env.step(action)
  33. # Test observation encode/decode roundtrip
  34. img = obs['image']
  35. grid = Grid.decode(img)
  36. img2 = grid.encode()
  37. assert np.array_equal(img2, img)
  38. # Check that the reward is within the specified range
  39. assert reward >= env.reward_range[0], reward
  40. assert reward <= env.reward_range[1], reward
  41. if done:
  42. env.reset()
  43. # Check that the agent doesn't overlap with an object
  44. assert env.grid.get(*env.agentPos) is None
  45. env.render('rgb_array')
  46. env.close()
  47. ##############################################################################
  48. env = gym.make('MiniGrid-Empty-6x6-v0')
  49. goalPos = (env.grid.width - 2, env.grid.height - 2)
  50. # Test the "in" operator on grid objects
  51. assert ('green', 'goal') in env.grid
  52. assert ('blue', 'key') not in env.grid
  53. # Test the env.agentSees() function
  54. env.reset()
  55. for i in range(0, 200):
  56. action = random.randint(0, env.action_space.n - 1)
  57. obs, reward, done, info = env.step(action)
  58. goalVisible = ('green', 'goal') in Grid.decode(obs['image'])
  59. assert env.agentSees(*goalPos) == goalVisible
  60. if done:
  61. env.reset()